#include <ESP32Servo.h>
#define MOTION_SENSOR_PIN 14 // ESP32 pin connected to motion sensor
#define SERVO1_PIN 27 // ESP32 pin connected to servo motor
#define SERVO2_PIN 12 // ESP32 pin connected to servo motor
// Define the pins for the LEDs
const int redLED_PIN = 18;
const int blueLED_PIN = 16;
Servo servo; // create servo object
int angle = 0; // current angle of the servo
int lastMotionState = LOW; // previous state of motion sensor
int currentMotionState = LOW; // current state of motion sensor
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(MOTION_SENSOR_PIN, INPUT); // motion sensor pin as input
pinMode(redLED_PIN, OUTPUT); // LED pin as output
servo.attach(SERVO1_PIN); // attach the servo motor
servo.write(angle); // move servo to 0°
digitalWrite(redLED_PIN, LOW); // ensure LED is OFF initially
currentMotionState = digitalRead(MOTION_SENSOR_PIN); // read initial state
Serial.begin(9600); // initialize serial communication
pinMode(MOTION_SENSOR_PIN, INPUT); // motion sensor pin as input
pinMode(blueLED_PIN, OUTPUT); // LED pin as output
servo.attach(SERVO2_PIN); // attach the servo motor
servo.write(angle); // move servo to 0°
digitalWrite(blueLED_PIN, HIGH); // ensure LED is OFF initially
currentMotionState = digitalRead(MOTION_SENSOR_PIN); // read initial state
}
void loop() {
lastMotionState = currentMotionState;
currentMotionState = digitalRead(MOTION_SENSOR_PIN); // read new state
if (currentMotionState == HIGH && lastMotionState == LOW) {
Serial.println("No Object detected! Rotating servo to 180°, LED ON");
servo.write(90); // rotate servo to 90°
digitalWrite(redLED_PIN, HIGH); // turn LED ON
}
else if (currentMotionState == LOW && lastMotionState == HIGH) {
Serial.println("No Object Detected! Rotating servo to 180°, LED OFF");
servo.write(0); // rotate servo to 0°
digitalWrite(redLED_PIN, LOW); // turn LED OFF
}
lastMotionState = currentMotionState;
currentMotionState = digitalRead(MOTION_SENSOR_PIN); // read new state
if (currentMotionState == HIGH && lastMotionState == LOW) {
Serial.println("Motion detected! Rotating servo to 0°, LED ON");
servo.write(90); // rotate servo to 90°
digitalWrite(blueLED_PIN, LOW); // turn LED ON
}
else if (currentMotionState == LOW && lastMotionState == HIGH) {
Serial.println("Motion stopped! Rotating servo to 0°, LED OFF");
servo.write(0); // rotate servo to 0°
digitalWrite(blueLED_PIN, HIGH); // turn LED OFF
}
delay(50); // small delay to stabilize reading
}