int pirPin = 2; // PIR sensor OUT pin connected to digital pin 2
int relayPin = 13; // Relay connected to digital pin 13
unsigned long lastMotionTime = 0; // Store the time of the last detected motion
const unsigned long motionTimeout = 180000; // 5 minutes (180000 milliseconds)
void setup() {
pinMode(2, INPUT); // Set PIR pin as input
pinMode(13, OUTPUT); // Set relay pin as output
digitalWrite(13, LOW); // Initialize relay to off
Serial.begin(9600); // Begin serial communication for debugging
}
void loop() {
int motionState = digitalRead(2); // Read PIR sensor state
unsigned long currentMillis = millis(); // Get the current time
if (motionState == HIGH) { // If motion is detected
digitalWrite(13, HIGH); // Turn on the relay (light)
lastMotionTime = currentMillis; // Update the time of the last motion
Serial.println("Motion detected! Light ON");
}
// Check if 5 minutes have passed since the last motion detection
if (currentMillis - lastMotionTime >= motionTimeout) {
digitalWrite(13, LOW); // Turn off the relay (light)
Serial.println("No motion for 5 minutes. Light OFF");
}
delay(100); // Small delay to avoid bouncing
}