const int triggerPin = 2;
const int echoPin = 3;
const int LED1 = 4;
const int LED2 = 5;
const int LED3 = 6;
long durasi;
int jarak;
void setup() {
pinMode(triggerPin, OUTPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
durasi = pulseIn(echoPin, HIGH);
jarak = durasi*0.034/2;
if(jarak > 50){
Serial.println("Jarak lebih dari 50cm");
digitalWrite(LED1, HIGH);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
}else if(jarak <= 50 && jarak >= 20){
Serial.println("Jarak berada diantara 20cm hingga 50cm");
digitalWrite(LED2, HIGH);
digitalWrite(LED1, LOW);
digitalWrite(LED3, LOW);
}else if(jarak < 20){
Serial.println("Jarak kurang dari 20cm");
digitalWrite(LED3, HIGH);
digitalWrite(LED2, LOW);
digitalWrite(LED1, LOW);
}
}