int trigPin = 2;
int echoPin = 3;
int buzzer = 13;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
if (distance <= 399)// if the distance is less than 30 or = 30
//than the buzzer will make sound
{
digitalWrite(buzzer,HIGH);
Serial.print(distance);//to print the distance in serial moniter
Serial.println("");
}
else {
digitalWrite(buzzer,LOW);//else it will turn off
Serial.print(distance);//to print the distance in serial moniter
Serial.println("");
}
delay(10);
}