// Define pins for ultrasonic sensor
const int trigPin = 9; // Trigger pin
const int echoPin = 10; // Echo pin
int buzzerpin = 8;
// Variables for duration and distance
long duration;
int distance;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set trigPin as an output and echoPin as an input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerpin, OUTPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to trigger the sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
digitalWrite(buzzerpin, HIGH);
// Measure the duration of the pulse on the echoPin
duration = pulseIn(echoPin, HIGH);
// Calculate distance in centimeters
distance = duration * (0.034 / 2);
// Print the distance to the serial monitor
Serial.print("Distance from the obstacle: ");
Serial.print(distance);
Serial.println(" cm");
// Wait before taking another reading
delay(500);
}