#include // Include the Servo library Servo lidServo; // Create a servo
object // Pin definitions const int trigPin = 10; // Trigger pin for ultrasonic
sensor const int echoPin = 11; // Echo pin for ultrasonic sensor const int
servoPin = 9; // PWM pin for servo motor const int ledPin = 12; // Optional:
LED for visual feedback long duration; // Variable for pulseIn() duration float
distance; // Variable for calculated distance in cm void setup()
{ [Link](9600); // Start serial communication for debugging
[Link](servoPin); // Attach the servo to its pin pinMode(trigPin,
OUTPUT); // Set trigPin as an output pinMode(echoPin, INPUT); // Set echoPin
as an input pinMode(ledPin, OUTPUT); // Set LED pin as an output // Initial
state: Lid closed (adjust angle as needed for your setup) [Link](20);
digitalWrite(ledPin, LOW); } void loop() { // --- Measure Distance ---
digitalWrite(trigPin, LOW); // Ensure trigger pin is low delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Send ultrasonic pulse delayMicroseconds(10);
digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); // Read the
echo pulse distance = 0.034 * (duration / 2); // Calculate distance (cm) // ---
Control Lid --- if (distance < 27) { // If object is within 27 cm (adjust as
needed) digitalWrite(ledPin, HIGH); // Turn LED on [Link](180); //
Open the lid (adjust angle for your servo) delay(3000); // Keep lid open for 3
seconds (adjust as needed) } else { digitalWrite(ledPin, LOW); // Turn LED off
[Link](20); // Close the lid (return to initial position) } delay(100); //
Short delay to prevent rapid re-triggering }