// Pin assignments
const int lightSensorPin = A0; // LDR connected to A0 for detecting light (CFL/natural light)
const int soundSensorPin = A1; // Sound sensor connected to A1
const int ledPin = 7; // LED connected to pin 7 (representing the night lamp bulb)
const int servoPin = 9; // Servo motor connected to pin 9 (for door lock)
int lightSensorValue = 0; // Variable to store the LDR value
int soundSensorValue = 0; // Variable to store the sound sensor value
int lightThreshold = 300; // Threshold for LDR to detect darkness (adjust as needed)
int soundThreshold = 500; // Threshold for sound detection (adjust as needed)
// PWM values for servo positions
int lockPosition = 100; // PWM value for the locked position (approx. 90 degrees)
int unlockPosition = 0; // PWM value for the unlocked position (approx. 0 degrees)
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as an output
pinMode(servoPin, OUTPUT); // Set the servo pin as an output
digitalWrite(ledPin, LOW); // Turn off the LED initially
Serial.begin(9600); // Start serial communication for debugging
Serial.println("System started. Monitoring light, sound, and door lock...");
}
void loop() {
lightSensorValue = analogRead(lightSensorPin); // Read the LDR value
soundSensorValue = analogRead(soundSensorPin); // Read the sound sensor value
// Display the light and sound values on the Serial Monitor for debugging
Serial.print("Light: ");
Serial.print(lightSensorValue); // Print LDR value for debugging
Serial.print(" | Sound: ");
Serial.println(soundSensorValue); // Print sound sensor value for debugging
// Check if sound is detected
if (soundSensorValue > soundThreshold) {
Serial.println("Don't Disturb! Locking door...");
// Lock the door (rotate the servo to lock position)
lockDoor(); // Function to lock the door (PWM for 90 degrees)
// Check if the room is dark (low LUX)
if (lightSensorValue > lightThreshold) {
digitalWrite(ledPin, HIGH); // Turn on the LED (night lamp)
} else {
digitalWrite(ledPin, LOW); // Keep the LED off if LUX is high
}
} else {
// If no sound is detected
digitalWrite(ledPin, LOW); // Turn off the LED
// Unlock the door (rotate the servo to unlock position)
unlockDoor(); // Function to unlock the door (PWM for 0 degrees)
}
delay(500); // Small delay for stability
}
// Function to lock the door (send PWM signal to servo)
void lockDoor() {
analogWrite(servoPin, lockPosition); // Send PWM signal to lock (90 degrees)
delay(1000); // Hold the position for 1 second
analogWrite(servoPin, 0); // Stop sending PWM signal
}
// Function to unlock the door (send PWM signal to servo)
void unlockDoor() {
analogWrite(servoPin, unlockPosition); // Send PWM signal to unlock (0 degrees)
delay(1000); // Hold the position for 1 second
analogWrite(servoPin, 0); // Stop sending PWM signal
}