#include <ESP32Servo.h>
#define MOTION_SENSOR_PIN 22
#define SERVO_PIN 26
Servo servo;
int angle = 0;
int lastMotionState = LOW;
int currentMotionState = LOW;
void setup() {
Serial.begin(9600);
pinMode(MOTION_SENSOR_PIN, INPUT);
servo.attach(SERVO_PIN);
servo.write(angle);
currentMotionState = digitalRead(MOTION_SENSOR_PIN);
lastMotionState = currentMotionState;
Serial.println("System ready...");
}
void loop() {
lastMotionState = currentMotionState;
currentMotionState = digitalRead(MOTION_SENSOR_PIN);
// Motion detected (LOW → HIGH)
if (currentMotionState == HIGH && lastMotionState == LOW) {
Serial.println("Motion detected! Rotating servo to 90°");
servo.write(90);
}
// Motion stopped (HIGH → LOW)
else if (currentMotionState == LOW && lastMotionState == HIGH) {
Serial.println("Motion stopped! Rotating servo to 0°");
servo.write(0);
}
delay(50); // small debounce
}