#include <ESP32Servo.h>
const int PIR_PIN = 14;
const int TRIGGER_PIN = 16;
const int ECHO_PIN = 5;
const int SERVO_PIN = 4;
const int DISTANCE_THRESHOLD = 10; // Distance threshold in centimeters
const int SERVO_OPEN_ANGLE = 90; // Angle for the servo to open the lid
const int SERVO_CLOSE_ANGLE = 0; // Angle for the servo to close the lid
const int SERVO_DELAY = 1000; // Delay before closing the lid (in milliseconds)
Servo servo;
void setup() {
Serial.begin(9600);
pinMode(PIR_PIN, INPUT);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
servo.attach(SERVO_PIN);
servo.write(SERVO_CLOSE_ANGLE); // Initially close the lid
}
void loop() {
if (detectMotion()) {
if (checkDistance() <= DISTANCE_THRESHOLD) {
openLid();
delay(SERVO_DELAY);
closeLid();
} else {
Serial.println("Object detected, but it's too far.");
}
} else {
Serial.println("No motion detected.");
}
}
bool detectMotion() {
return digitalRead(PIR_PIN) == HIGH;
}
float checkDistance() {
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
return pulseIn(ECHO_PIN, HIGH) / 58.0; // Calculate distance in centimeters
}
void openLid() {
servo.write(SERVO_OPEN_ANGLE);
Serial.println("Lid opened");
}
void closeLid() {
servo.write(SERVO_CLOSE_ANGLE);
Serial.println("Lid closed");
}