#define PIN_TRIG 3
#define PIN_ECHO 2
#define LED_MERAH 13 // Red LED for full trash
#define LED_HIJAU 12 // Green LED for not full
void setup() {
Serial.begin(115200); // Set baud rate for serial communication
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
pinMode(LED_MERAH, OUTPUT);
pinMode(LED_HIJAU, OUTPUT);
}
float getDistance() {
// Trigger the ultrasonic sensor
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Measure the echo time
int echoDuration = pulseIn(PIN_ECHO, HIGH);
// Calculate distance in cm
return echoDuration * 0.034 / 2;
}
void loop() {
float distance = getDistance();
Serial.println(distance); // To debug and see the measured distance
// Condition to check if trash is 53 cm or less (turn red LED on)
if (distance <= 53) { // Trash level is at or below 53 cm
digitalWrite(LED_MERAH, HIGH); // Turn on red LED (trash is full)
digitalWrite(LED_HIJAU, LOW); // Turn off green LED
}
else if (distance > 53 && distance <= 400) { // Trash level is above 53 cm
digitalWrite(LED_MERAH, LOW); // Turn off red LED
digitalWrite(LED_HIJAU, HIGH); // Turn on green LED (trash is not full)
} else {
// If the distance is beyond sensor range, turn off both LEDs as an error indication
digitalWrite(LED_MERAH, LOW);
digitalWrite(LED_HIJAU, LOW);
}
delay(500); // Short delay for sensor reading
}