#define ECHO_PIN 2
#define TRIG_PIN 3
#define pinRelay 4
float X=400/397.63;
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(pinRelay, LOW);
}
void loop() {
//Generate ultrasonic signal
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
//Read ultrasonic signal
int duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 * X / 2;
Serial.print("Jarak: ");
Serial.print(distance);
Serial.println(" CM");
if(distance < 20)
{
Serial.println("Merah (Mati)");
digitalWrite(pinRelay, LOW);
}
else if (distance >= 100 )
{
Serial.println("Hijau (Nyala)");
digitalWrite(pinRelay, HIGH);
}
else{
Serial.println("Kuning");
}
delay(500);
}