#define TRIG 5
#define ECHO 18
#define ALERT_PIN 13 // LED or buzzer
float binHeight = 400.0; // total bin height in cm
float alertThreshold = 80.0; // alert when fill% > 80
void setup() {
Serial.begin(115200);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(ALERT_PIN, OUTPUT);
digitalWrite(ALERT_PIN, LOW); // start with alert OFF
}
// Get distance from ultrasonic sensor
float getDistance() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long duration = pulseIn(ECHO, HIGH, 30000); // 30 ms timeout
if (duration == 0) return binHeight; // no echo, assume empty
float distance = duration * 0.0343 / 2; // convert to cm
// Safety clamp
if (distance > binHeight) distance = binHeight;
if (distance < 0) distance = 0;
return distance;
}
void loop() {
float distance = getDistance();
float fill = ((binHeight - distance) / binHeight) * 100.0;
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm | Fill: ");
Serial.print(fill);
Serial.println("%");
// ALERT LOGIC
if (fill >= alertThreshold) {
Serial.println("ALERT! Bin is almost full!");
digitalWrite(ALERT_PIN, HIGH); // LED ON / buzzer ON
} else {
digitalWrite(ALERT_PIN, LOW); // LED OFF / buzzer OFF
}
delay(1000); // 1 second between measurements
}