#define TRIG_PIN 1 // Trigger pin of ultrasonic sensor (GPIO 2)
#define ECHO_PIN 2 // Echo pin of ultrasonic sensor (GPIO 3)
void setup() {
// Start serial communication for debugging
Serial.begin(115200);
// Set up the pins for the ultrasonic sensor
pinMode(TRIG_PIN, OUTPUT); // Trigger pin as OUTPUT
pinMode(ECHO_PIN, INPUT); // Echo pin as INPUT
}
void loop() {
// Send a pulse to the TRIG pin to start the ultrasonic measurement
digitalWrite(TRIG_PIN, LOW); // Ensure the trigger is off initially
delayMicroseconds(2); // Wait for 2ms
digitalWrite(TRIG_PIN, HIGH); // Send a 10us HIGH pulse to trigger the sensor
delayMicroseconds(10); // Wait for 10ms
digitalWrite(TRIG_PIN, LOW); // Turn off the trigger signal
// Measure the duration of the pulse that comes back from the ECHO pin
long duration = pulseIn(ECHO_PIN, HIGH); // Read the pulse width
// Calculate the distance using the formula: distance = (duration / 2) * speed of sound
// Speed of sound is approximately 343 meters per second (or 0.0343 cm/µs)
long distance = (duration / 2) * 0.0343; // Divide by 2 to get the round-trip distance
// Print the distance in cm to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a bit before taking the next reading
delay(500); // Delay 500ms to avoid flooding the Serial Monitor
}