#include <Servo.h>
#define ECHO_PIN 7
#define TRIG_PIN 8
#define pinBuzzer 2
Servo myservo;
void setup() {
pinMode(TRIG_PIN, OUTPUT);// put your setup code here, to run once:
pinMode(ECHO_PIN, INPUT);
pinMode(pinBuzzer, OUTPUT);
Serial.begin(115200);
myservo.attach(12);
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(10);
digitalWrite(ECHO_PIN, HIGH);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
float distance = readDistanceCM();// put your main code here, to run repeatedly:
Serial.println("JARAK SENSOR");
if (distance <= 200){
myservo.write(90);
delay(25);
tone (pinBuzzer,1000);
delay(200);
}
else {
myservo.write(0);
noTone(pinBuzzer);
}
}