#include <Servo.h>.
const int trigPin = 10;
const int echoPin = 9;
const int buzzer = 8;
// defining time and distance
long duration;
int distance;
int safetyDistance ;
Servo myServo; // Object servo
void setup() {
pinMode(trigPin, OUTPUT); // trigPin as an Output
pinMode(echoPin, INPUT); // echoPin as an Input
pinMode ( buzzer , OUTPUT ) ;
Serial.begin(9600);
myServo.attach(7); // Pin Connected To Servo
}
void loop() {
// rotating servo i++ depicts increment of one degree
for(int i=0;i<=180;i++){
myServo.write(i);
delay(30);
distance = calculateDistance();
Serial.print(i);
Serial.print(",");
Serial.print(distance);
Serial.print(".");
safetyDistance = distance ;
if ( safetyDistance >= 10 ) {
digitalWrite ( buzzer , HIGH ) ;
delay(0.5);
}
else {
digitalWrite ( buzzer , LOW ) ;
delay(0);
}
}
// Repeats the previous lines from 180 to 0 degrees
for(int i=180;i>=0;i–){
myServo.write(i);
delay(30);
distance = calculateDistance();
Serial.print(i);
Serial.print(",");
Serial.print(distance);
Serial.print(".");
safetyDistance = distance ;
if ( safetyDistance >= 10 ) {
digitalWrite ( buzzer , HIGH ) ;
delay(0.5);
}
else {
digitalWrite ( buzzer , LOW ) ;
delay(0);
}
}
}
int calculateDistance(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
return distance;
}
it’s should notify me in right angle by vibrate 1 time “buz” , and notify again in the left angle by vibrate 2 time"buz"