#define BUZZ 4
#define ECHO_PIN 2
#define TRIG_PIN 15

// int BUZZ = 4;
// int ECHO_PIN = 2;
// int TRIG_PIN = 15;
int LED_1 = 27;
int LED_2 = 14;
int LED_3 = 12;
int LED_4 = 13;

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LED_1, OUTPUT);
  pinMode(LED_2, OUTPUT);
  pinMode(LED_3, OUTPUT);
  pinMode(LED_4, OUTPUT);
  pinMode(BUZZ, OUTPUT);
  digitalWrite(LED_1, LOW);
  digitalWrite(LED_2, LOW);
  digitalWrite(LED_3, LOW);
  digitalWrite(LED_4, LOW);
}

float readDistanceCM(int TRIG, int ECHO) {
  int duration;
  float distance;
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  duration = pulseIn(ECHO, HIGH);
  // Serial.print("Durasi: ");
  // Serial.println(duration);
  return distance = duration * 0.034 / 2;
}

void loop() {
  float distance = readDistanceCM(TRIG_PIN, ECHO_PIN);
  Serial.print("Jarak: ");
  Serial.println(distance);

  if(distance > 300){
    digitalWrite(LED_1, HIGH);
    digitalWrite(LED_2, HIGH);
    digitalWrite(LED_3, HIGH);
    digitalWrite(LED_4, HIGH);
    tone(BUZZ, 1000);
  } else if((distance > 200) && (distance <= 300)){
    digitalWrite(LED_1, HIGH);
    digitalWrite(LED_2, HIGH);
    digitalWrite(LED_3, HIGH);
    digitalWrite(LED_4, LOW);
    noTone(BUZZ);
  } else if((distance > 100) && (distance <= 200)){
    digitalWrite(LED_1, HIGH);
    digitalWrite(LED_2, HIGH);
    digitalWrite(LED_3, LOW);
    digitalWrite(LED_4, LOW);
    noTone(BUZZ);
  } else if(distance > 50){
    digitalWrite(LED_1, HIGH);
    digitalWrite(LED_2, LOW);
    digitalWrite(LED_3, LOW);
    digitalWrite(LED_4, LOW);    
    noTone(BUZZ);
  } else {
    digitalWrite(LED_1, LOW);
    digitalWrite(LED_2, LOW);
    digitalWrite(LED_3, LOW);
    digitalWrite(LED_4, LOW);
    noTone(BUZZ);
  }
  delay(500);
}