// Define pins for the ultrasonic sensor
const int trigPin = 9; // Trigger pin
const int echoPin = 10; // Echo pin
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set up the trigger pin as an output
pinMode(trigPin, OUTPUT);
// Set up the echo pin as an input
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigger pin high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the pulse duration from the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
float distance = duration * 0.0344 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a short period before the next measurement
delay(500);
}