// Define pins for the ultrasonic sensor
const int trigPin = 3; // Trigger pin
const int echoPin = 2; // Echo pin
// Define pin for the buzzer
const int buzzerPin = 7;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to the trigger pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the duration of the pulse on the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
int distance = duration / 58.2;
// Check if an object is within a certain range (e.g., 20 centimeters)
if (distance < 200) {
// If an object is detected within the specified range, sound the buzzer
digitalWrite(buzzerPin, HIGH);
delay(1000); // Sound the buzzer for 1 second
digitalWrite(buzzerPin, LOW);
}
// Print the distance to the serial monitor for monitoring
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Delay for a moment before taking the next reading
delay(100);
}