#define pintriger 5
#define pinecho 22
#define buzzer 13
#define LED1 15
#define LED2 18
#define LED3 21
void setup() {
Serial.begin (115200); //Inisialisasi komunikasi serial
//Deklarasi pin
pinMode(pintriger, OUTPUT);
pinMode(pinecho, INPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(buzzer, OUTPUT);
}
void loop() {
digitalWrite(pintriger, LOW);
delayMicroseconds(2);
digitalWrite(pintriger, HIGH);
delayMicroseconds(10);
digitalWrite(pintriger, LOW);
long durasi = pulseIn(pinecho, HIGH);
long jarak = (durasi/2) / 29;
Serial.print(jarak);
Serial.println (" cm");
if (jarak < 50)
{
digitalWrite(LED1,LOW);
digitalWrite(LED2,LOW);
digitalWrite(LED3,LOW);
digitalWrite(buzzer, LOW);
}
if (jarak > 50 && jarak < 100)
{
digitalWrite(LED1,HIGH);
digitalWrite(LED2,LOW);
digitalWrite(LED3,LOW);
digitalWrite(buzzer, LOW);
}
if (jarak > 100 && jarak < 200)
{
digitalWrite(LED1,HIGH);
digitalWrite(LED2,HIGH);
digitalWrite(LED3,LOW);
digitalWrite(buzzer, LOW);
}
if (jarak > 200 && jarak < 300)
{
digitalWrite(LED1,HIGH);
digitalWrite(LED2,HIGH);
digitalWrite(LED3,HIGH);
digitalWrite(buzzer, LOW);
}
if (jarak > 300)
{
digitalWrite(LED1,HIGH);
digitalWrite(LED2,HIGH);
digitalWrite(LED3,HIGH);
digitalWrite(buzzer, HIGH);
}
delay(1000);
}