const int pirPin = 4; // PIR sensor output connected to ESP32 GPIO15 (D15 on NodeMCU board)
const int buzzerPin = 5; // Buzzer connected to ESP32 GPIO3 (D3 on NodeMCU board)
const int ledPinred = 18; // Red LED connected to ESP32 GPIO18 (D18 on NodeMCU board)
const int ledPingreen = 15; // Green LED connected to ESP32 GPIO15 (D15 on NodeMCU board)
const int buttonPin = 13; // Pushbutton connected to ESP32 GPIO13 (D13 on NodeMCU board)
void setup() {
pinMode(pirPin, INPUT); // Set PIR sensor pin as input
pinMode(buzzerPin, OUTPUT); // Set buzzer pin as output
pinMode(ledPinred, OUTPUT); // Set red LED pin as output
pinMode(ledPingreen, OUTPUT); // Set green LED pin as output
pinMode(buttonPin, INPUT);// Set pushbutton pin as input with internal pull-up resistor
Serial.begin(115200); // Initialize serial communication for debugging (optional)
}
void loop() {
int pirState = digitalRead(pirPin); // Read the state of the PIR sensor
if (pirState == HIGH) { // If motion is detected
Serial.println("Motion detected!");
for (int i = 0; i < 100; i++) { // Blink the red LED and the buzzer 10 times
digitalWrite(ledPingreen, LOW);
digitalWrite(ledPinred, HIGH); // Turn on the red LED
analogWrite(buzzerPin, 128); // Turn on the Buzzer with 50% duty cycle (adjust the value as needed for the desired sound)
delay(200); // Keep the red LED and buzzer on for 200 milliseconds
digitalWrite(ledPinred, LOW); // Turn off the red LED
analogWrite(buzzerPin, 0); // Turn off the Buzzer (0 duty cycle means off)
delay(200); // Keep the red LED and buzzer off for 200 milliseconds
// Check if the pushbutton is pressed
if (digitalRead(buttonPin) == HIGH) {
Serial.println("Button pressed!");
analogWrite(buzzerPin, 0); // Turn off the Buzzer (0 duty cycle means off)
delay(200); // Keep the green LED and buzzer off for 200 milliseconds
break;
}
}
} else {
digitalWrite(ledPingreen, HIGH);
Serial.println("No motion detected.");
delay(200); // Small delay to reduce false detections (optional)
}
}