// Declare the variables
int pirPin = 14; // PIR sensor output pin
int lightPin = 13; // Relay or LED pin
unsigned long motionDetectedTime = 0; // Time when motion was last detected
unsigned long delayTime = 30000; // Delay (30 seconds) before turning off lights
bool lightOn = false; // Track the light state (on/off)
void setup() {
// Initialize serial monitor for debugging
Serial.begin(115200);
// Set up PIR sensor and light pin modes
pinMode(pirPin, INPUT);
pinMode(lightPin, OUTPUT);
// Start with lights off
digitalWrite(lightPin, LOW);
}
void loop() {
// Read the PIR sensor
int pirState = digitalRead(pirPin);
if (pirState == HIGH) { // Motion detected
Serial.println("Motion detected!");
// Turn on the light if it's not already on
if (!lightOn) {
digitalWrite(lightPin, HIGH); // Turn on the light (activate relay or LED)
lightOn = true; // Update light state
}
// Update the last motion detected time
motionDetectedTime = millis();
}
// Check if it's time to turn off the lights
if (lightOn && (millis() - motionDetectedTime > delayTime)) {
Serial.println("Turning off lights...");
digitalWrite(lightPin, LOW); // Turn off the light
lightOn = false; // Update light state
}
delay(100); // Small delay for debouncing the PIR sensor
}