///Define the pins for the ultrasonic sensor
const int trigPin = 9; // Trigger pin
const int echoPin = 10; //Echopin
int buzzer = 11;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(trigPin, OUTPUT); // set Trigger pin
pinMode(echoPin, INPUT); // set echopin
pinMode(buzzer, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//MEasure the time taken for the pulse to
long duration = pulseIn(echoPin, HIGH);
//calculate
//speed oif sound
// distance
int distance = duration * 0.0343 / 2;
//Print the distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(100);
if(distance>100)
{
digitalWrite(buzzer, 0);
}
else if(distance>25)
{
digitalWrite(buzzer, 1);
tone(buzzer, 500, 400);
delay(400);
digitalWrite(buzzer, 0);
tone(buzzer, 500, 400);
delay(400);
}
else
{
digitalWrite(buzzer, 1);
tone(buzzer, 1000, 100);
delay(100);
digitalWrite(buzzer, 0);
tone(buzzer, 1000, 100);
delay(100);
}
}