// Define Pins
const int trigPin = 9;
const int echoPin = 10;
const int servoPin = 11;
// Define Variables
long duration;
int distance;
// Set up the servo
#include <Servo.h>
Servo myservo;
void setup() {
// Set up the pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myservo.attach(servoPin);
// Wait for the servo to be in the closed position
myservo.write(0);
delay(5000);
}
void loop() {
// Send a pulse to the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the time it takes for the pulse to return
duration = pulseIn(echoPin, HIGH);
// Calculate the distance based on the speed of sound
distance = duration * 0.034 / 2;
// If an object is detected, open the lid
if (distance < 10) {
myservo.write(90);
delay(3000);
myservo.write(0);
}
}