#include <Servo.
h>
// Pin Definitions
Const int trigPin = 9;
Const int echoPin = 10;
Const int servoPin = 6;
// Parameters
Const int detectionThreshold = 20; // Distance in cm to trigger lid open
Const unsigned long closeDelay = 3000; // Time in ms to keep lid open after last
detection
// Global Variables
Servo lidServo;
Long duration;
Int distance;
Bool isLidOpen = false;
Unsigned long lastDetectionTime = 0;
Void setup() {
// Initialize Sensor Pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Attach Servo and Close Lid
lidServo.attach(servoPin);
lidServo.write(0); // 0 degrees = closed position
// Start Serial Monitor (for debugging)
Serial.begin(9600);
Void loop() {
// Measure Distance with Ultrasonic Sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Convert to cm
// Print Distance for Debugging
Serial.print(“Distance: “);
Serial.print(distance);
Serial.println(“ cm”);
// Control Lid Based on Distance
If (distance <= detectionThreshold && distance > 0) {
If (!isLidOpen) {
lidServo.write(90); // Open lid (90 degrees)
isLidOpen = true;
Serial.println(“Lid opened!”);
lastDetectionTime = millis(); // Reset timer
} else {
If (isLidOpen && (millis() – lastDetectionTime > closeDelay)) {
lidServo.write(0); // Close lid
isLidOpen = false;
Serial.println(“Lid closed!”);
Delay(100); // Short delay to stabilize readings