#include <Servo.h>
Servo servo;
const int trigPin = 6; // Ultrasonic sensor trigger pin
const int echoPin = 5; // Ultrasonic sensor echo pin
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo.attach(3); // Servo attached to pin 3
// Initialize serial communication
Serial.begin(9600);
}
void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // 10µs pulse for reliable trigger
digitalWrite(trigPin, LOW);
// Measure the pulse input in echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate distance (half the duration divided by 29.1 from datasheet)
distance = (duration/2) / 29.1;
// Determine and display trash level indication
if (distance < 400 && distance >= 300) {
Serial.println("Bin is nearly full"); // Bin is nearly full
} else if (distance > 100 && distance <= 300) {
Serial.println("Bin is moderately full"); // Bin is moderately full
} else if (distance > 0 && distance <= 100) {
Serial.println("Bin is mostly empty"); // Bin is mostly empty
} else {
Serial.println("Bin is full");
}
// Servo control for dustbin lid
if (distance <= 50 && distance >= 0) {
servo.write(90); // Open lid (adjust angle as needed)
delay(2000); // Keep lid open for 2 seconds
} else {
servo.write(0); // Close lid (adjust angle as needed)
}
delay(100); // Small delay to stabilize readings
}