#include <Servo.h>
Servo myservo;
#define TRIG_PIN 5
#define ECHO_PIN 4
#define BUZZ_PIN 8
int pinBuzzer = 8;
int nilai;
void setup() {
// put your setup code here, to run once:
myservo.attach(6);
pinMode(pinBuzzer, OUTPUT);
pinMode(BUZZ_PIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(9600);
}
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 loop() {
// put your main code here, to run repeatedly:
float distance = readDistanceCM();
Serial.print("Jarak Kereta Api : ");
Serial.println(readDistanceCM());
//delay(100);
if (distance>200){
myservo.write(90);
delay(15);
tone(pinBuzzer, 1000);
delay(100);
tone(pinBuzzer, 500);
delay(200);
}else{
myservo.write(0);
noTone(pinBuzzer);
}
}