Ultrasonic timeouts and invalid readings
Illustrative workshop cover.

Ultrasonic timeouts and invalid readings

Treat a missing echo as missing information, not as a zero-distance object or a clear path.

The HC-SR04 estimates distance from the time between sending sound and receiving its reflection. Its ECHO pulse represents the outward and return journey, so divide the travelled distance by two. A room-temperature approximation is duration in microseconds multiplied by 0.0343 and divided by two to obtain centimeters. Temperature and target geometry affect accuracy.

A trigger HIGH pulse of at least 10 microseconds initiates a reading. Leave time between readings; the supplied parking demo uses 100 ms between trigger starts. Do not repeatedly retrigger as fast as loop can run. The manufacturer recommends a measurement cycle longer than 60 ms.

Always choose an explicit timeout for pulseIn. The demo uses 25,000 microseconds, so no echo does not hold the loop for a long default timeout. A returned duration of zero is invalid. Do not convert it into an apparently precise zero-centimeter measurement, which would make a disconnected sensor look like a very close object.

Validate the application range as well as the timeout. The parking demo accepts 2–200 cm, deliberately narrower than the sensor's nominal range. Report missing or rejected readings separately from valid readings. The LED is off both for an invalid reading and a distant valid target; therefore its light state alone is not evidence of a clear path.

Check with a flat target at known distances using a ruler. Angle the target, move it near the minimum range and remove it from view. Record which cases yield a valid echo. Small, soft or badly angled objects may reflect poorly. Repeated identical numbers can indicate stale values rather than perfect stability.

On a 5V UNO, the demo uses the normal ECHO connection. Do not copy that direct connection to a 3.3V ESP32 GPIO; use appropriate voltage reduction and check the exact module. Disconnect power before moving sensor wires, and read the board labels for pin order.

For a more advanced project, keep the time of the most recent valid sample and expire it. Filtering must not turn a stream of failed readings into a permanently retained old distance. This classroom demo is not a vehicle parking system. Reference: HC-SR04 manufacturer datasheet: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf