Ultrasonic Ranging with HC-SR04
Ultrasonic Ranging with HC-SR04
Overview
Section titled “Overview”The HC-SR04 is a cheap ultrasonic ranging module, a good entry point for liquid level, obstacle avoidance and presence detection. Its traps are not in the principle but in the dead zone, echo quality and the 5 V output. By the end of this section you will be able to:
- Compute distance from echo timing and put the temperature correction for sound speed into code
- Judge which targets simply cannot be measured, and what to do when an echo times out
- Connect Echo to an ESP32 safely, and weigh divider versus level shifter
- Run several modules on one device without them hearing each other
Prerequisites
Section titled “Prerequisites”Before starting this section, make sure you:
- Completed Sections 1 and 3 of Chapter 25
- Have an HC-SR04 module (VCC/Trig/Echo/GND) and a tape measure
- Have a foam pad or thick book for the “absorbent / angled target” control test
Key Concepts
Section titled “Key Concepts”One sentence of principle, two lines of formula
Section titled “One sentence of principle, two lines of formula”The module emits eight 40 kHz bursts; Echo stays high for the round-trip flight time:
distance = time × speed of sound / 2- Speed varies with temperature; the engineering approximation is
v ≈ 331.4 + 0.6 × Tm/s (T in °C)
At 25 °C that is about 346 m/s. Without temperature compensation, a 30 °C span introduces roughly 5 % distance error — right at an alarm threshold, that means “it does not sound when it should”.
Constraint 1: dead zone and range
Section titled “Constraint 1: dead zone and range”- Dead zone ≈ 2 cm: for very close objects the echo would arrive while the module is still transmitting, so readings are invalid
- Nominal ceiling 2–4 m (some batches state 4.5 m); beyond that echo energy is insufficient and timeouts are normal, not a fault
- Typical accuracy sits between millimetre and centimetre level (module manuals often quote ±3 mm) — do not use it as a metrology device
Write both limits into the design document; it is far cheaper than later explaining “why it stops working closer than 2 cm”.
Constraint 2: the target surface decides success
Section titled “Constraint 2: the target surface decides success”Ultrasound relies on reflection, so surface properties dominate:
| Target | Result | Handling |
|---|---|---|
| Flat hard surface (water, metal, glass) | Strong echo, stable readings | Ideal case |
| Slanted surface, off-normal angle | Reflection deflected, weak or missing echo | Correct mounting angle, or accept occasional timeouts |
| Soft absorbent material (foam, fabric, clothes) | Energy absorbed, often no echo at all | Change sensing principle (IR, capacitive level) |
| Thin rods, cables | Reflection cross-section too small | Add a reflector plate, or change principle |
| Froth on liquid, dusty surfaces | Jitter or inflated readings | Statistical filtering plus a “consecutive invalid” alarm |
A timeout is information, not a failure: firmware must report “no echo” as a state instead of silently reusing the last frame.
Constraint 3: Echo is 5 V logic
Section titled “Constraint 3: Echo is 5 V logic”Echo’s high level follows the module supply (5 V), while ESP32 GPIO is not 5 V tolerant. Three options:
- Resistive divider: e.g. 2.2 kΩ upper plus 1.5 kΩ lower brings 5 V down to about 2.0 V. Cheap, but the divider network plus pin capacitance adds a few microseconds of timing skew — tolerable for centimetre-level ranging, unacceptable if you depend on pulse-width precision.
- One-way level shifter: a 2-channel board or a dedicated part. Clean timing, guaranteed thresholds — the product-grade choice.
- Buy a 3.3 V variant: improved modules with on-board level adaptation exist (pinout and footprint may differ, verify the specification before ordering), removing the work in options 1 and 2.
Rule: dividers for teaching and prototypes; level shifters or 3.3 V modules for products, recorded in the wiring sheet.
Multiple modules must be serialised
Section titled “Multiple modules must be serialised”Two HC-SR04 units transmitting simultaneously interpret each other’s burst as an echo, producing phantom near distances. Reliable approach: serialise polling, one module at a time with at least 60 ms between cycles (the manual’s recommended minimum). If you need higher dynamics or immunity, move to a different principle (ToF, mmWave radar).
Power: burst current and decoupling
Section titled “Power: burst current and decoupling”Idle draw is on the order of tens of milliamps, with transmit peaks in the tens-to-over-a-hundred milliamp range. Sharing a rail with Wi-Fi, or feeding through long thin wiring, commonly shows up as “occasional dropped frames plus module reboot”. Fix: 100 µF electrolytic plus 100 nF ceramic placed close to the module, dedicated supply routing, and a solid common ground.
Implementation
Section titled “Implementation”Basic ranging with a timeout
Section titled “Basic ranging with a timeout”const uint8_t TRIG_PIN = 12;const uint8_t ECHO_PIN = 13; // Echo must pass through a divider or level shifterconst unsigned long TIMEOUT_US = 30000; // 30 ms ≈ 5 m round trip; beyond that treat as no echo
float speedOfSound() { float tC = 25.0f; // replace with a real temperature reading, see below return 331.4f + 0.6f * tC;}
// Returns distance in centimetres; -1 means no valid echofloat readDistanceCm() { digitalWrite(TRIG_PIN, LOW); delayMicroseconds(3); digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(12); // manual requires ≥10 µs digitalWrite(TRIG_PIN, LOW);
unsigned long us = pulseIn(ECHO_PIN, HIGH, TIMEOUT_US); if (us == 0) return -1; // timeout: not "0 cm", but "nothing measured" return us * 0.00001f * speedOfSound() / 2.0f * 100.0f;}
void setup() { Serial.begin(115200); pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT);}
void loop() { float cm = readDistanceCm(); if (cm < 0) { Serial.println("range: no echo (out of range or absorbent target)"); } else if (cm < 2.0f) { Serial.println("range: inside dead zone, ignore"); } else { Serial.printf("range: %.1f cm\n", cm); } delay(80); // measurement cycle above 60 ms}pulseIn itself blocks until timeout, up to about 30 ms. For genuinely non-blocking operation, capture Echo’s rising and falling edges in an interrupt, record micros() deltas, and turn ranging into an event so the main loop is never occupied.
Wiring in the temperature correction (reuse Section 4)
Section titled “Wiring in the temperature correction (reuse Section 4)”float speedOfSoundFromAmbient() { float tC = lastValidTempC; // latest valid temperature from DS18B20 / SHT3x if (isnan(tC)) return 343.0f; // no temperature: fall back to ~20 °C nominal return 331.4f + 0.6f * tC;}When temperature is unavailable, degrade explicitly to the nominal value and mark the state as “no compensation” — never keep an stale correction coefficient alive because it looks fine.
Polling three modules
Section titled “Polling three modules”const uint8_t NUM_SENSORS = 3;const uint8_t TRIGS[NUM_SENSORS] = {12, 14, 16};const uint8_t ECHOS[NUM_SENSORS] = {13, 15, 17};
float distances[NUM_SENSORS];
void pollAll() { for (uint8_t i = 0; i < NUM_SENSORS; i++) { digitalWrite(TRIGS[i], LOW); delayMicroseconds(3); digitalWrite(TRIGS[i], HIGH); delayMicroseconds(12); digitalWrite(TRIGS[i], LOW); unsigned long us = pulseIn(ECHOS[i], HIGH, 30000); distances[i] = us ? us * 0.00001f * speedOfSound() / 2.0f * 100.0f : -1.0f; delay(70); // serialised gap, prevents cross-hearing }}Statistical filtering and validity
Section titled “Statistical filtering and validity”float medianOf9(float *buf) { // simple sort, take the middle value — robust to occasional dropouts and phantom near reads for (uint8_t i = 0; i < 8; i++) for (uint8_t j = 0; j < 8 - i; j++) if (buf[j] > buf[j + 1]) { float t = buf[j]; buf[j] = buf[j + 1]; buf[j] = t; } return buf[4];}Suggested rules: report “no target” only after 3 consecutive timeouts, update the level only after 5 stable median frames, and discard single-frame jumps beyond 30 % while counting them — an excess of such events should raise a “target surface or mounting anomaly” alarm.
Verification
Section titled “Verification”| Check | Expected result | Verified |
|---|---|---|
| Tape measure at 10 / 30 / 100 / 300 cm | ≤1 cm error in the 10–30 cm band, ≤3 cm beyond 1 m (empirical, confirm by measurement) | |
| Target at 1 cm | Falls into the dead zone and must be rejected, not reported as 1 cm | |
| Facing a 5 cm foam pad | Echo lost, the no echo branch is hit |
|
| Rotate the target 30° | Jitter or loss, demonstrating angle sensitivity | |
Two modules transmitting together (remove delay(70)) |
Phantom near readings appear — proof the crosstalk is real | |
| Ambient temperature 20 °C → 40 °C | Without compensation readings bias by about 3–5 %, validating the correction | |
| Compare with and without local 100 µF + 100 nF | Dropout rate decreases (proving the supply is the cause) |
The last two rows are my standard checks when a customer asks “why does it occasionally lose frames”; run them on every installation and keep the record.
Troubleshooting
Section titled “Troubleshooting”Issue 1: readings stuck at 0 or at a constant value
Section titled “Issue 1: readings stuck at 0 or at a constant value”Symptoms: continuous zeros, or one frozen number.
Possible causes:
pulseIntimed out and returned 0, which the code multiplied into a distance (treating “not measured” as “0 cm”)- Wrong divider ratio, so the Echo high level sits under the threshold and no pulse is detected
- Trig and Echo swapped
Solutions:
- Separate the states:
us == 0must return “invalid” and never enter the conversion - Check Echo high-level amplitude with a meter or scope; confirm it is above ~2 V
- Re-verify wiring against the silkscreen: Trig is an input, Echo is an output
Issue 2: values jump, with occasional absurdly close readings
Section titled “Issue 2: values jump, with occasional absurdly close readings”Symptoms: stable numbers interrupted by 5 cm or 10 cm outliers.
Possible causes:
- Multiple modules or other 40 kHz sources in the environment (other devices, tap noise) interfering
- Multiple reflections inside a vessel creating ghost echoes
- Supply ripple destabilising the transmit burst
Solutions:
- Serialise the polling cycle to ≥60 ms and keep only valid frames
- Tilt the sensor 5–10° to avoid mirror-like reflections
- Add local decoupling; if jitter persists, apply median filtering plus a 30 % jump rejection and report the anomaly rate
Issue 3: no readings at long range, fine at short range
Section titled “Issue 3: no readings at long range, fine at short range”Symptoms: beyond 2–3 m there is rarely an echo.
Cause: beam spread and reflection energy decay with distance — a physical limit.
Solutions:
- Above ~4 m change principle (laser ToF, mmWave radar) rather than pushing supply voltage
- Add a reflector plate (flat hard surface) to boost echo energy
- State the reliable range and dead zone explicitly in the design document to prevent out-of-spec use
Issue 4: the controller resets when ranging starts
Section titled “Issue 4: the controller resets when ranging starts”Symptoms: ESP32 restarts or Wi-Fi drops at the moment of transmission.
Cause: transmit peak current pulls the rail down and triggers brown-out reset.
Solutions:
- Power the module from its own regulator with a solid common ground
- Increase local energy storage capacitance
- Confirm it is a supply issue and not software — print the reset reason (e.g.
esp_sleep_get_reset_reason) instead of guessing
Best Practices
Section titled “Best Practices”- Do: report timeout, dead zone and out-of-range as three distinct states; never let an invalid frame masquerade as a value
- Do: in products, always use a level shifter or a 3.3 V module, and record it in the wiring and selection sheets
- Do: apply temperature compensation, and document where the temperature sensor sits relative to the ultrasonic path
- Do: serialise multi-module polling, and hard-code the ≥60 ms cycle with an explanatory comment
- Don’t: use the HC-SR04 for millimetre metrology or as a safety anti-collision sensor
- Don’t: judge the module’s health using a soft absorbent target — that is a principle limit, not a defect
- Don’t: mount the transducer flush against an enclosure wall; mechanical resonance degrades readings
Summary
Section titled “Summary”Key points of this section:
- Distance comes from echo timing, and the sound-speed temperature term (≈331.4 + 0.6×T m/s) governs long-range accuracy
- About 2 cm dead zone, reliable to 2–4 m; beyond that there is simply no echo, and both limits belong in the design document
- Target surface decides success: flat hard surfaces are best; angled, absorbent or thin targets drop frames
- Echo is 5 V logic — dividers suit prototypes, level shifters suit products, or buy a 3.3 V variant outright
- Serialised multi-module polling plus supply decoupling are the two hard requirements for stability; invalid frames must be states, not numbers
Next section: proximity and presence — from IR proximity to mmWave radar, and the range-versus-privacy trade-off.
We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.
💡 Mention tutorial.imagrove.com in your Alibaba chat with us — get 10% off your custom project quote.
First published attutorial.imagrove.com/sensor-module-selection/07-ultrasonic-ranging-with-hc-sr04/Please credit Imagrove and link back to this page when quoting or republishing.
Questions or issues with this tutorial?
Sign in with GitHub to leave a comment. If a step fails for you, tell us — we verify it and update the tutorial.
© Imagrove · ESP32 IoT Tutorial