#define pinTrig 2
#define pinEcho 3
#define pinLEDMerah 8
#define pinLEDKuning 7
#define pinLEDHijau 6

void setup() {
  Serial.begin(9600);

  pinMode(pinTrig, OUTPUT);
  pinMode(pinEcho, INPUT);

  pinMode(pinLEDMerah, OUTPUT);
  pinMode(pinLEDKuning, OUTPUT);
  pinMode(pinLEDHijau, OUTPUT);


}

void loop() {  
  if (bacaSensorJarak() > 300) {
    // air rendah
    digitalWrite(pinLEDMerah, LOW);
    digitalWrite(pinLEDKuning, LOW);
    digitalWrite(pinLEDHijau, HIGH);    

    Serial.println("Jarak Halangan: " + String(bacaSensorJarak()));
    Serial.println("Air Dangkal");
  } else if (bacaSensorJarak() > 150 && bacaSensorJarak() <= 300) {
    // air sedang
    digitalWrite(pinLEDMerah, LOW);
    digitalWrite(pinLEDKuning, HIGH);
    digitalWrite(pinLEDHijau, LOW);    

    Serial.println("Jarak Halangan: " + String(bacaSensorJarak()));
    Serial.println("Air Sedang");
  } else if (bacaSensorJarak() <= 150) {
    // air rendah
    digitalWrite(pinLEDMerah, HIGH);
    digitalWrite(pinLEDKuning, LOW);
    digitalWrite(pinLEDHijau, LOW);

    Serial.println("Jarak Halangan: " + String(bacaSensorJarak()));
    Serial.println("Air Tinggi silahkan evakuasi!");
  }  
  delay(100);
}


float bacaSensorJarak() {
  digitalWrite(pinTrig, LOW);
  delayMicroseconds(2);

  digitalWrite(pinTrig, HIGH);
  delayMicroseconds(10);

  digitalWrite(pinTrig, LOW);

  int duration = pulseIn(pinEcho, HIGH);
  return duration * 0.0344 / 2;
}