#define ECHO 3
#define TRIG 2
#define BUZZ 5
#define MLED 11
#define KLED 10
#define HLED 8
#include <Servo.h>
float X =1.006;
Servo myservo;

int potpin= 0;
int val;

float readDistanceCM() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int duration = pulseIn(ECHO, HIGH);
return duration * 0.034 * X / 2;
}

void loop() {
  float distance = readDistanceCM();
  Serial.print("Jarak Sensor: ");
  Serial.println(readDistanceCM());
  Serial.println(" Cm");
  delay(100);

  if(distance <= 200){
    myservo.write(90);
    digitalWrite(MLED, HIGH);
  delay(15);
  tone(BUZZ, 100);
  delay(500);
  tone(BUZZ, 100);
  delay(500);
  tone(BUZZ, 100);
  delay(100);
  tone(BUZZ, 1000);
  }

  else if(distance <= 200) {
  digitalWrite(MLED, HIGH);
  digitalWrite(KLED, LOW);
  digitalWrite(HLED, LOW);
  }

  else if(distance <= 300){
    digitalWrite(KLED, HIGH);
    delay(100);
    digitalWrite(KLED, LOW);
    digitalWrite(MLED, LOW);
    digitalWrite(HLED, LOW);
  }
  if(distance >= 300){
    digitalWrite(HLED, HIGH);
  }
  else{
  myservo.write(0);
  noTone(BUZZ);
  }
}

void setup() {
  pinMode(TRIG, OUTPUT); 
  pinMode(ECHO, INPUT); 
  pinMode(MLED, OUTPUT);
  pinMode(KLED, OUTPUT);
  pinMode(HLED, OUTPUT);
  Serial.begin(115200); 
  pinMode(BUZZ, OUTPUT); 
  myservo.attach(9); 
  }