#define led 13
int buzzer = 12;
#define trig 11
#define echo 10
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
// put your setup code here, to run once:
pinMode(trig,OUTPUT);
pinMode(echo, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
// Clears the trigPin condition
digitalWrite(trig, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echo, HIGH);
// Calculating the distance
distance = duration * 0.0340 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance > 300){
digitalWrite(led, HIGH);
tone(buzzer,1000);
delay(1000);
digitalWrite(led, LOW);
noTone(buzzer);
delay(1000);
Serial.println(" Status: Bak Kosong");
}
if(distance<100){
digitalWrite(led, HIGH);
tone(buzzer,500);
delay(1000);
digitalWrite(led, LOW);
noTone(buzzer);
delay(1000);
Serial.println(" Status: Bak Penuh");
}
}