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 > 300){
Serial.println("Jarak lebih dari 300cm");
digitalWrite(LED1, HIGH);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
}
else if(jarak <= 300 && jarak >= 100){
Serial.println("Jarak berada diantara 100cm hingga 300cm");
digitalWrite(LED2, HIGH);
digitalWrite(LED1, LOW);
digitalWrite(LED3, LOW);
}
else if(jarak < 100){
Serial.println("Jarak kurang dari 100cm");
digitalWrite(LED3, HIGH);
digitalWrite(LED2, LOW);
digitalWrite(LED1, LOW);
}
}