#define servoPin 3
#define ultraPin 2
#define buzzerPin 5
#include <Servo.h>
Servo myservo;
int rotation = 90;
int interval = 0;
float readDistanceCM(){
digitalWrite(ultraPin, LOW);
delayMicroseconds(2);
digitalWrite(ultraPin, HIGH);
delayMicroseconds(10);
digitalWrite(ultraPin, LOW);
int duration = pulseIn(servoPin, HIGH);
return duration * 0.034/2;
}
void soundBuzzer(){
if(interval < 500){
tone(buzzerPin, 250);
}else
if(interval > 500){
tone(buzzerPin, 100,800);
};
}
void setup() {
// put your setup code here, to run once:
pinMode(ultraPin, OUTPUT);
pinMode(servoPin, INPUT);
Serial.begin(115200);
pinMode(buzzerPin, OUTPUT);
myservo.attach(9);
myservo.write(90);
}
void loop() {
// put your main code here, to run repeatedly:
tutupPalang();
interval +=100;
if(interval>1000) interval = 0;
}
void tutupPalang(){
float jarak = readDistanceCM();
if(jarak > 0 && jarak < 100 ){
soundBuzzer();
tutup();
}else{
buka();
noTone(buzzerPin);
}
}
void tutup(){
if(rotation <= 90){
myservo.write(rotation);
delay(100);
rotation--;
}
if(rotation <= 0 ) rotation = 0;
}
void buka(){
if(rotation <= 90){
myservo.write(rotation);
delay(100);
rotation+=4;
}
if(rotation >= 90 ) rotation = 90;
}