int const trigPin = 10; // Defines the data pins of the ultrasonic
int const echoPin = 9;
int const buzzPin = 2; // Defines the buzzer pin
void setup()
{
pinMode(trigPin, OUTPUT); // sets trig pin to have output pulses
pinMode(echoPin, INPUT); // sets echo pin to be input and get the pulse width
pinMode(buzzPin, OUTPUT); // sets buzz pin as output to control the sound
}
void loop()
{
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration * 0.0344 / 2;
if (distance > 0 && distance < 51)
{
tone(buzzPin, 8000, 500);
}
else
{
noTone(buzzPin);
}
}