//deklarasikan pin input
#define ECHO_PIN 3
#define TRIG_PIN 2
#define pinBuzzer 5
//gunakan library servo
#include <Servo.h>
Servo palang;
int potpin = 0;
int val;
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 setup () {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(115200);
pinMode(pinBuzzer, OUTPUT);
palang.attach(4);
}
void loop() {
//baca jarak
float distance = readDistanceCM();
Serial.print("Jarak Kereta Api:");
Serial.println(readDistanceCM());
//kondisi logika apakah dibawah 200
if(distance <= 200){
palang.write(90);
delay(15);
tone(pinBuzzer, 500);
delay(1000);
tone(pinBuzzer, 800);
delay(1000);
}
else{
palang.write(0);
noTone(pinBuzzer);
}
val = analogRead(potpin);
val = map(val, 0, 1023, 0, 90);
palang.write(val);
delay(15);
}