// Define pins for sensors and relay
const int LDRPin = 2; // Digital pin connected to the LDR module
const int PIRPin1 = 3; // Digital pin connected to the first PIR sensor
const int PIRPin2 = 5; // Digital pin connected to the second PIR sensor
const int PIRPin3 = 6; // Digital pin connected to the third PIR sensor
const int PIRPin4 = 12; // Digital pin connected to the fourth PIR sensor
const int PIRPin5 = 10; // Digital pin connected to the fifth PIR sensor
const int relayPin = 4; // Digital pin connected to the relay that controls the light
// Time settings
unsigned long motionDetectedTime = 0; // The last time motion was detected
unsigned long lightOnDuration = 5000; // Duration to keep the light on after detecting motion (in milliseconds)
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Set the sensor pins as inputs
pinMode(LDRPin, INPUT);
pinMode(PIRPin1, INPUT);
pinMode(PIRPin2, INPUT);
pinMode(PIRPin3, INPUT);
pinMode(PIRPin4, INPUT);
pinMode(PIRPin5, INPUT);
// Set the relay pin as output
pinMode(relayPin, OUTPUT);
// Initially turn off the light
digitalWrite(relayPin, LOW);
}
void loop() {
// Read the state of the LDR (0 if dark, 1 if light)
int LDRState = digitalRead(LDRPin);
// Read the state of the PIR sensor (0 if no motion, 1 if motion detected)
int PIRState1 = digitalRead(PIRPin1);
int PIRState2 = digitalRead(PIRPin2);
int PIRState3 = digitalRead(PIRPin3);
int PIRState4 = digitalRead(PIRPin4);
int PIRState5 = digitalRead(PIRPin5);
// Print the states to the Serial Monitor for debugging
Serial.print("LDR State: ");
Serial.print(LDRState);
Serial.print(", PIR1 State: ");
Serial.println(PIRState1);
Serial.print(", PIR2 State: ");
Serial.println(PIRState2);
Serial.print(", PIR3 State: ");
Serial.println(PIRState3);
Serial.print(", PIR4 State: ");
Serial.println(PIRState4);
Serial.print(", PIR5 State: ");
Serial.println(PIRState5);
// Check if it's dark
if (LDRState == HIGH) {
// If motion is detected by any PIR sensor, update the last motion detected time
if (PIRState1 == HIGH || PIRState2 == HIGH || PIRState3 == HIGH ||PIRState4 == HIGH || PIRState5 == HIGH) {
motionDetectedTime = millis(); // Record the current time
digitalWrite(relayPin, HIGH); // Turn on the light
Serial.println("Light ON - Motion detected");
}
// Keep the light on if motion was detected within the last 'lightOnDuration'
if (millis() - motionDetectedTime <= lightOnDuration) {
digitalWrite(relayPin, HIGH); // Keep the light on
} else {
digitalWrite(relayPin, LOW); // Turn off the light if no motion was detected within the time period
Serial.println("Light OFF - No recent motion");
}
}
// If it's not dark, ensure the light stays off
else {
digitalWrite(relayPin, LOW);
Serial.println("Light OFF - It's daytime");
}
// Short delay for stability
delay(100);
}