#define ECHO_PIN 3
#define TRIG_PIN 2
#define pinBuzzer 5
#define ledM 13
#include <Servo.h>
Servo myservo;
int val = 0;
int x = true;
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);
pinMode(ledM, OUTPUT);
myservo.attach(11);
}
void loop(){
float distance = readDistanceCM();
Serial.print("Jarak: ");
Serial.println(readDistanceCM());
if(distance <= 100){
if(x == true)
{
val = val+10;
myservo.write(val);
}
delay(15);
tone(pinBuzzer, 1000);
digitalWrite(ledM, HIGH);
delay(200);
tone(pinBuzzer, 500);
digitalWrite(ledM, LOW);
delay(200);
}
else{
myservo.write(0);
noTone(pinBuzzer);
if(val == 90)
{
val = 0;
x = true;
}
}
}