#include <Servo.h>
int trigPin = 9; // TRIG pin for ultrasonic sensor
int echoPin = 8; // ECHO pin for ultrasonic sensor
int servoPin = 11; // Pin for the servo motor
Servo myServo; // Create a servo object
void setup() {
Serial.begin(9600); // Start serial communication
pinMode(trigPin, OUTPUT); // Set TRIG pin as output
pinMode(echoPin, INPUT); // Set ECHO pin as input
myServo.attach(servoPin); // Attach the servo to the specified pin
// Initialize the servo to the closed position (0 degrees)
myServo.write(0);
delay(1000); // Wait for the servo to reach the position
}
void loop() {
long duration, distance;
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
distance = (duration * 0.0343) / 2; // Speed of sound is 0.0343 cm/µs
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check the distance and control the servo
if (distance < 20) { // If an object is detected within 20 cm
myServo.write(90); // Open the lid (adjust angle as needed)
Serial.println("Lid Opened");
Serial.println (" ");
} else {
myServo.write(0); // Close the lid
Serial.println("Lid Closed");
Serial.println (" ");
}
delay(500); // Wait for half a second before the next measurement
}