#define  ECHO_PIN 3
#define  TRIG_PIN 2
#define pinBuzzer 5
#define pinLampu 6

#include <Servo.h>

Servo myservo;
int rotasi = 90;
int interval = 0;

float 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;
}

void soundBuzzer(){
  if(interval < 500){
    tone(pinBuzzer, 250);
  }else if(interval > 500){
    tone(pinBuzzer, 100, 800);
  }
}

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(115200);
  pinMode(pinBuzzer, OUTPUT);
  pinMode(pinLampu, OUTPUT);
  myservo.attach(9);
  myservo.write(90);
}

void loop() {
  tutupPalang();
  interval += 100;
  if(interval > 1000) interval = 0;
}

void tutupPalang(){
  float jarak = readDistanceCM();
  if(jarak > 0 && jarak < 100){
    soundBuzzer();
    tutup();
    digitalWrite(pinLampu, HIGH); // Menyalakan lampu saat kereta mendekat
    delay(500);
    digitalWrite(pinLampu, LOW); // Mematikan lampu
    delay(500);
  }else{
    buka();
    noTone(pinBuzzer);
    digitalWrite(pinLampu, LOW); // Mematikan lampu saat kereta menjauh
  }
}

void tutup(){
  if(rotasi > 0){
    myservo.write(rotasi);
    delay(10); // Mengurangi penundaan agar servo bergerak lebih cepat
    rotasi--;
  }
  if(rotasi <= 0) rotasi = 0;
}

void buka(){
  if(rotasi < 90){
    myservo.write(rotasi);
    delay(10); // Mengurangi penundaan agar servo bergerak lebih cepat
    rotasi += 4;
  }
  if(rotasi >= 90) rotasi = 90;
}