#define ECHO_PIN 5
#define TRIG_PIN 4
#define Merah 8
#define Kuning 7
#define Hijau 6

float X=400/397.63;

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(Merah, OUTPUT);
  pinMode(Kuning, OUTPUT);
  pinMode(Hijau, OUTPUT);
}

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");

  digitalWrite(Merah, LOW);
  digitalWrite(Hijau, LOW);
  digitalWrite(Kuning, LOW);

  //Cara 1
  if(distance < 50)
  {
   Serial.println("Merah (Bahaya)");
   digitalWrite(Merah, HIGH);
   }
   else if (distance < 100)
   {
   Serial.println("Kuning (Waspada)");
   digitalWrite(Kuning, HIGH);
   }
   else 
   {
   Serial.println("Hijau (Normal)");
   digitalWrite(Hijau, HIGH);
   }

  // Cara 2
  //if( distance > 50 && distance < 150)
  //{
    //Serial.println("Kuning (Waspada)");
    //digitalWrite(Kuning, HIGH);
  //}
  //else if (distance > 0 && distance < 50)
  //{
    //Serial.println("Merah (Bahaya)");
    //digitalWrite(Merah, HIGH);
  //}
  //else 
  //{
    //Serial.println("Hijau (Normal)");
    //digitalWrite(Hijau, HIGH);
  //}

  delay(500);
}