#define TRIG_PIN 23 // ESP32 pin GPIO23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 22 // ESP32 pin GPIO22 connected to Ultrasonic Sensor's ECHO pin
#define MAX_DISTANCE_CM 400 // Maximum distance supported by the sensor (adjust based on sensor specifications)
float duration_us, distance_cm;
void setup() {
// begin serial port
Serial.begin(9600);
// configure the trigger pin to output mode
pinMode(TRIG_PIN, OUTPUT);
// configure the echo pin to input mode
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// generate a 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(5);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// measure the duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance
distance_cm = duration_us * 0.034 / 2;
// check for out-of-range measurements
if (distance_cm >= 2 && distance_cm <= MAX_DISTANCE_CM) {
// print the value to Serial Monitor
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
} else {
// print out-of-range message
Serial.println("Out of range");
}
delay(500);
}