const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 8;
const long distanceThreshold = 50; // Distance threshold in centimeters
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
// Initialize buzzer to off
digitalWrite(buzzerPin, LOW);
}
void loop() {
// Send a pulse to trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin and calculate the distance
long duration = pulseIn(echoPin, HIGH);
long distance = (duration * 0.034) / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn on the buzzer if the distance is less than the threshold
if (distance < distanceThreshold) {
digitalWrite(buzzerPin, HIGH);
} else {
digitalWrite(buzzerPin, LOW);
}
// Wait for 500 milliseconds before the next reading
delay(500);
}