// Define the pins for the ultrasonic sensor
const int trigPin = 2; // Trigger pin
const int echoPin = 3; // Echo pin
// Define the pin for the buzzer
const int buzzerPin = 4;
// Variables for the duration and distance
long duration;
int distance;
void setup() {
// Set up the serial communication
Serial.begin(9600);
// Set up the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set up the buzzer pin
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// Generate ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than a threshold
if (distance < 10) {
// If the distance is less than 10 cm, turn on the buzzer
digitalWrite(buzzerPin, HIGH);
} else {
// Otherwise, turn off the buzzer
digitalWrite(buzzerPin, LOW);
}
// Delay before the next measurement
delay(1000);
}