#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-
#include <Servo.h>
Servo myservo;
#define servo 6
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
int buzzer = 5;
void setup()
{
myservo.attach(servo);
pinMode(buzzer, OUTPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // Serial Communication is starting with 9600 of baudrate speed
}
void loop(){
// put your main code here, to run repeatedly:
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH); // Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
int i = 90;
if (distance < 50) {
tone(buzzer, 1000);
myservo.write(i);
delay(10);
Serial.println(("on"));
}
else {
myservo.write(0);
delay(10);
noTone(buzzer);
}
}