// Define pin numbers
#define TRIG_PIN 9 // Trigger pin (connected to digital pin 9)
#define ECHO_PIN 10 // Echo pin (connected to digital pin 10)
long duration; // Duration of the pulse in microseconds
int distance; // Distance to the object in centimeters
void setup() {
// Initialize the serial communication
Serial.begin(9600);
// Set the TRIG pin as an OUTPUT and ECHO pin as INPUT
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Send a 10 microsecond pulse to the TRIG pin to initiate measurement
digitalWrite(TRIG_PIN, LOW); // Ensure the trigger is LOW initially
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(TRIG_PIN, HIGH); // Send a HIGH signal to start the pulse
delayMicroseconds(10); // Pulse width is 10 microseconds
digitalWrite(TRIG_PIN, LOW); // Set the TRIG pin LOW again
// Measure the time it takes for the pulse to return
duration = pulseIn(ECHO_PIN, HIGH); // Measure the duration of the pulse on the ECHO pin
// Calculate the distance in centimeters
distance = (duration / 2) / 29.1; // Distance = (time / 2) * speed of sound (in cm/us)
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Delay before taking another measurement
delay(500);
}