#include <ESP32Servo.h>
// Pin definitions
#define TRIG_PIN 4 // Trig pin for HC-SR04
#define ECHO_PIN 5 // Echo pin for HC-SR04
#define SERVO_PIN 2 // Servo control pin
// Create Servo object
Servo myServo;
// Define constants
const int OPEN_ANGLE = 90; // Servo open position
const int CLOSE_ANGLE = 0; // Servo closed position
const int DISTANCE_THRESHOLD = 20; // Distance threshold in cm
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Configure pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Attach servo to the defined pin
myServo.attach(SERVO_PIN);
// Set initial servo position (closed)
myServo.write(CLOSE_ANGLE);
}
void loop() {
// Measure distance using the ultrasonic sensor
long distance = measureDistance();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Open or close the trash can based on distance
if (distance > 0 && distance < DISTANCE_THRESHOLD) {
myServo.write(OPEN_ANGLE); // Open the trash can
delay(3000); // Keep open for 3 seconds
} else {
myServo.write(CLOSE_ANGLE); // Close the trash can
}
delay(100); // Short delay for sensor stability
}
// Function to measure distance using HC-SR04
long measureDistance() {
// Send a 10us pulse to TRIG_PIN
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the pulse width on ECHO_PIN
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm
long distance = duration * 0.034 / 2;
return distance;
}