#include <avr/sleep.h>
const int pirPin = 3; // PIR sensor pin connected to interrupt 1 (digital pin 3)
const int ledPin = 13; // LED pin
volatile bool motionDetected = false; // Flag to indicate motion detection
volatile bool keepLEDOn = false; // Flag to keep the LED on after 1 second
unsigned long lastMotionTime = 0; // Variable to store the time of the last motion detection
unsigned long lastMotionOffTime = 0; // Variable to store the time of the last motion-off event
void setup() {
Serial.begin(9600); // Start serial communication
pinMode(ledPin, OUTPUT); // LED pin as output
pinMode(pirPin, INPUT_PULLUP); // PIR sensor pin as input with pull-up resistor
attachInterrupt(digitalPinToInterrupt(pirPin), motionDetected_ISR, RISING); // Attach interrupt for rising edge
}
void loop() {
if (motionDetected) {
Serial.println("Motion detected!"); // Debug message
digitalWrite(ledPin, HIGH); // Turn LED on
lastMotionOffTime = millis(); // Record the time of motion detection
while (millis() - lastMotionOffTime <= 1000) {
// Keep the LED on for 1 second after motion detected
// Check if motion still detected during this time
if (digitalRead(pirPin) == LOW) {
// Motion stopped, no need to keep the LED on
keepLEDOn = false;
break; // Exit the while loop
}
keepLEDOn = true; // Motion detected, keep the LED on
}
if (!keepLEDOn) {
// Turn off the LED if no need to keep it on
digitalWrite(ledPin, LOW); // Turn LED off
}
motionDetected = false; // Reset motion detection flag
}
// Check if 5 seconds have elapsed since the last motion detection
if (millis() - lastMotionOffTime > 5000 && digitalRead(ledPin) == HIGH) {
// If no motion detected for 5 seconds and LED is on, turn off the LED
digitalWrite(ledPin, LOW); // Turn LED off
}
}
void motionDetected_ISR() {
motionDetected = true; // Set motion detection flag
lastMotionTime = millis(); // Record the time of motion detection
}