int jarak_maksimal = 10; //cm


#include <Servo.h>
#define ECHO_PIN 2
#define TRIG_PIN 3
int lastDuration;
Servo servo;

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  servo.attach(4);
}

int readDistanceCM() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  int duration = pulseIn(ECHO_PIN, HIGH);
  //return duration * 0.034 / 2;
  return duration / 58;
}


void loop() {
  int duration = readDistanceCM();
  if (lastDuration == duration) return;
  lastDuration = duration;

  if (duration < jarak_maksimal) {
    servo.write(90);
    delay(1000);
  } else servo.write(0);


  Serial.print("Measured distance: ");
  Serial.println(readDistanceCM());
}