#include <Servo.h>
const int trig = 9;
const int echo = 10;
const int servoPin = 11;
Servo binLid;
const int openAngle = 90;
const int closeAngle = 0;
const int thresholdDistance = 50;
void setup() {
Serial.begin(9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
binLid.attach(servoPin);
binLid.write(closeAngle);
}
void loop() {
long duration, distance;
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = (duration * 0.034 / 2);
Serial.print("Distance: ");
Serial.println(distance);
if (distance <= thresholdDistance) {
binLid.write(openAngle);
} else {
binLid.write(closeAngle);
}
delay(500);
}