#include <Servo.h>
#define ECHO_PIN 3
#define TRIG_PIN 2
#define pinBuzzer 5
Servo myservo;
int potpin = 0;
int pos;
int buzzerPin = 5;
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);
myservo.attach(9);
}
void loop() {
if (readDistanceCM() < 100){
for (pos = 0; pos <= 90; pos += 1){
myservo.write(pos);
delay(15);
//tone(buzzerPin, 150);
//delay(15);
}
noTone(buzzerPin);
delay(1000);
}else if (readDistanceCM() > 100){
for (pos = 90; pos >= 0; pos -= 1){
myservo.write(pos);
delay(15);
noTone(buzzerPin);
}
}
}