// Define pin numbers
const int motionSensorPin = 2; // Pin connected to the OUT of the PIR sensor
const int ledPin = 13; // Pin connected to the anode of the LED
const int buzzerPin = 12; // Pin connected to the positive terminal of the buzzer
// Define timing variables
unsigned long motionDetectedTime = 0; // To store the time when motion was last detected
const unsigned long delayDuration = 30000; // 30 seconds delay duration
// Define the states
bool ledState = false; // Track the current state of the LED
bool motionDetected = false; // Track whether motion is detected
void setup() {
pinMode(motionSensorPin, INPUT); // Set PIR sensor pin as input
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buzzerPin, OUTPUT); // Set buzzer pin as output
digitalWrite(ledPin, LOW); // Ensure LED is off initially
digitalWrite(buzzerPin, LOW); // Ensure buzzer is off initially
}
void loop() {
int motionState = digitalRead(motionSensorPin); // Read the state of the PIR sensor
if (motionState == HIGH) {
// Motion detected
if (!motionDetected) {
// If motion was not previously detected, turn on the LED and beep the buzzer
digitalWrite(ledPin, HIGH);
digitalWrite(buzzerPin, HIGH); // Turn on the buzzer
delay(100); // Keep the buzzer on for 100 milliseconds
digitalWrite(buzzerPin, LOW); // Turn off the buzzer
ledState = true; // Update LED state
motionDetected = true; // Update motion detected flag
motionDetectedTime = millis(); // Record the time of detection
}
} else {
// No motion detected
motionDetected = false; // Update motion detected flag
}
// Check if 30 seconds have passed since motion was last detected
if (ledState && (millis() - motionDetectedTime >= delayDuration)) {
digitalWrite(ledPin, LOW); // Turn off the LED
ledState = false; // Update LED state
}
}