#include <ESP32Servo.h>
// Define the pin connections for the components
const int pirPin = 14;
const int ledPin = 2;
const int buzzerPin = 12;
const int servoPin = 27;
// Create a servo object
Servo myservo;
void setup() {
// Initialize the serial communication
Serial.begin(115200);
// Set the pin modes
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Attach the servo to the corresponding pin
myservo.attach(servoPin);
// Initialize the servo position
myservo.write(90);
// Wait for the servo to move to its initial position
delay(1000);
}
void loop() {
// Read the PIR sensor value
int pirValue = digitalRead(pirPin);
if (pirValue == HIGH) {
Serial.println("Motion detected!");
// Turn on the LED
digitalWrite(ledPin, HIGH);
// Play a tone on the buzzer
tone(buzzerPin, 1000, 500);
// Move the servo to a new position
myservo.write(180);
delay(1000);
myservo.write(0);
delay(1000);
myservo.write(90);
// Wait for a moment before resetting the components
delay(5000);
// Turn off the LED and buzzer
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
}
// Wait for a short moment before checking the PIR sensor again
delay(100);
}