// Define the pins for the ultrasonic sensor
const int trigPin = 9;
const int echoPin = 10;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Define pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a pulse to the trigger pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
unsigned long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
// Speed of sound = 343 m/s or 34300 cm/s
// Distance = (Time * Speed) / 2
float distance = (duration * 34300.0) / (2.0 * 1000000.0); // Convert to meters
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" meters");
delay(1000); // Wait for a short time before taking the next measurement
}