#include <Servo.h>
const int trigPin = 9; // Trig pin of the HC-SR04
const int echoPin = 10; // Echo pin of the HC-SR04
const int servoPin = 6; // Pin to which the servo motor is connected
Servo lidServo;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
lidServo.attach(servoPin);
}
void loop() {
long duration, distance;
// Triggering the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reading the echo pin to calculate distance
duration = pulseIn(echoPin, HIGH);
// Calculating distance in cm
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Opening the lid if an object or human is detected within 20cm
if (distance < 10) {
openLid();
delay(2000); // Wait for 2 seconds before closing the lid
closeLid();
}
}
void openLid() {
// Rotating the servo motor to open the lid
lidServo.write(90); // Adjust the angle as per requirement
}
void closeLid() {
// Rotating the servo motor to close the lid
lidServo.write(0); // Adjust the angle as per requirement
}