You failed to include a time limit for your function call. And you failed to test for ZERO being returned, meaning no echo in the allotted time. By not including a time-out time, you automatically get a one second time-out period.
I added a delay for duration_us, a delay before other mesurements and a check if the echo is received but I'm not sure if the logic is sound for that last one. It still return the same range of distance.
Trigger pulse sent.
Echo pulse received.
Distance: 53.18 cm, 20.94 inches
Trigger pulse sent.
Echo pulse received.
Distance: 50.51 cm, 19.88 inches
#define TRIG_PIN 5 // ESP32 pin GPIO connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 18 // ESP32 pin GPIO connected to Ultrasonic Sensor's ECHO pin
void setup() {
Serial.begin(115200); // Begin serial port with a higher baud rate for better precision
pinMode(TRIG_PIN, OUTPUT); // Configure the trigger pin to output mode
pinMode(ECHO_PIN, INPUT); // Configure the echo pin to input mode
}
void loop() {
long duration_us;
float distance_cm, distance_inch;
// Clear the trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Debug: The trigger pulse was sent
Serial.println("Trigger pulse sent.");
// Measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH, 300000); // 30 ms timeout
// Debug: Check if echo was received
if (duration_us > 0) {
Serial.println("Echo pulse received.");
// Calculate the distance in cm and inches
distance_cm = duration_us * 0.0343 / 2;
distance_inch = distance_cm * 0.393701;
// Print the calculated distances
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.print(" cm, ");
Serial.print(distance_inch);
Serial.println(" inches");
} else {
Serial.println("No echo received or out of range.");
}
delay(5000); // Wait before taking another measurement
}
I suggest you cross-check the sensor with an Arduino UNO. A full connection diagram and code is available here: Ultrasonic Sensor Arduino Interfacing - The Engineering Projects
Please try and see if the same problem persists. If yes, I believe, it's a dead sensor.
Thank you for the suggestion, I took my old Duemilanove and hook it up with the code you provided. Plugged in 3.3v I had the same behavior, once plugged it in the 5v I got the right results. My Lolin S2 only output to 3.3v so I wont be able to use the sensor with that board unless I find another source of power.