Home / IoT, Sensors & ESP32 / HC-SR04 Ultrasonic Sensor with ESP32: Distance Done Right

HC-SR04 Ultrasonic Sensor with ESP32: Distance Done Right

IoT, Sensors & ESP32 ✍ Oliver Adam ⏱ 6 min read August 7, 2026

The HC-SR04 bounces 40 kHz sound off a target and times the echo. Distance = pulse_width × 343 m/s ÷ 2. Simple physics, three practical traps level shifting, mounting angles and noisy echoes.
> At a glance: 6 minute guide · part 7 of 10 in the complete IoT and ESP32 guide track · includes a worked example and a quick-reference table.

## Wiring and level shifting

Here is the working theory in one pass. Trigger and Echo are 5 V signals on the classic module; the ESP32 is a 3. 3 V part. Divide the Echo line (1 kΩ + 2 kΩ divider) or use a 3. 3 V-compatible variant. TRIG from the ESP32 drives the module fine at 3. 3 V logic.

| P | a | r | a | m | e | t | e | r |
| — | — | — | — | — | — | — | — | — |
| V | a | l | u | e | | | | |
| N | o | t | e | | | | | |
| Trigger pulse | 10 µs | Standard | | | | | | |
| Speed of sound | 343 m/s at 20 °C | ±0.6 %/°C drift | | | | | | |
| cm from µs | µs ÷ 58 | Rule of thumb | | | | | | |
| Range | 2 cm – 4 m | Soft/angled targets shrink it | | | | | | |
| Beam angle | ~15° | Keep clear of shrouds | | | | | | |

## Timing and conversion

Send a 10 µs trigger, then measure the Echo pulse with pulseIn(). Centimetres = pulse_µs ÷ 58. Timeouts matter: cap pulseIn at ~30 ms so a missing echo does not hang the loop. Reading faster than ~10 Hz interacts with the previous echo train.

## Mounting and filtering

Sound reflects off angled surfaces mount perpendicular to the target. Soft fabrics absorb; narrow gaps cause wall echoes. Median-filter five readings (drop the outlier) rather than averaging one wild echo ruins an average but vanishes in a median.

## How to apply this in your build

Work through the sequence below each step assumes the previous one passed. For numbers that need calculating, the linked tools at the end of this guide do the arithmetic instantly.
1. Level-shift Echo before connecting to ESP32 GPIO
2. Trigger, then pulseIn() with a 30 ms timeout
3. Convert with µs ÷ 58 for centimetres
4. Median-filter five samples before deciding anything

### Worked example

A water-tank gauge read 12 cm high whenever the surface rippled. Five-sample median filtering plus mounting the sensor off-centre removed the splash echoes and steadied readings to ±1 cm. Run the numbers yourself with the RC Time Constant and the result should agree to within rounding.

> Practical note from the bench. Median over mean is the Procirel default for any bouncy sensor ultrasonic, lidar, even noisy ADC channels.

## Common mistakes to avoid

– Connecting 5 V Echo straight to ESP32 GPIO
– No timeout on pulseIn a lost echo freezes the sketch
– Averaging without outlier rejection one bad echo poisons the result

## Key takeaways

Wiring and level shifting the foundation of this guide; revisit it if any measurement here surprises you.
Timing and conversion the foundation of this guide; revisit it if any measurement here surprises you.
Mounting and filtering the foundation of this guide; revisit it if any measurement here surprises you.

## Who this guide is for

Beginners get a single focused topic instead of a whole textbook chapter. It assumes the track’s earlier pages in the complete IoT and ESP32 guide path. Intermediate readers use it as a reference the table, the worked example and the mistake list answer the questions that come up mid-build. If you teach, the structure (theory, application, example, failure modes) maps cleanly onto a lab session.

## What you need before starting

Nothing exotic: the parts or tools named in the guide, a multimeter. The RC Time Constant open in a tab. Level-shift Echo before connecting to ESP32 GPIO before you begin the guide assumes it and keep the quick-reference table above within sight while you work through the steps.

### Quick reference card

| Aspect | Where to find it in this guide |
| — | — |
| Core theory | Wiring and level shifting |
| Application steps | How to apply this in your build |
| Worked numbers | Worked example |
| Failure modes | Common mistakes to avoid |

## How this fits the complete IoT and ESP32 guide track

This guide is one stop in the structured learning path. Start from the [complete IoT and ESP32 guide](/tutorial/iot-esp32-complete-guide) pillar page for the full map, or continue with [DHT22 climate sensing](/tutorial/dht22-temperature-humidity-esp32) and [ESP32 GPIO rules](/tutorial/esp32-gpio-strapping-pins). For the arithmetic, open the [RC Time Constant](/tools/rc-time-constant).

## Frequently asked questions

Can HC-SR04 work outdoors?
Humidity and temperature shift the speed of sound. Compensate the constant or accept ~2 % error, and protect the transducers from water.

What if I need more than 4 m?
Move to an industrial ultrasonic or ToF laser sensor (VL53L1X reaches 4 m too, but precisely).

Is there a calculator for this?
Yes the [RC Time Constant](/tools/rc-time-constant) tool runs the formulas from this guide instantly, client-side, with no signup.

## Continue the learning path

– The complete iot, sensors & esp32 guide: [IoT, Sensors & ESP32 complete guide](/tutorial/iot-esp32-complete-guide)
– Read next: [lorawan for beginners: long-range iot without wifi](/tutorial/lorawan-tutorial-beginners)
– Also in this track: [antenna basics for iot: wavelength, gain and matching](/tutorial/antenna-basics-tutorial)
– Continue with: [biomedical sensors: how wearables measure the body](/tutorial/biomedical-sensor-guide)
– Calculate as you go: [battery life estimator](/tools/battery-life) · [LM317 regulator designer](/tools/lm317-regulator) · [wire gauge checker](/tools/wire-gauge-awg)
– Bookmark this page against the day a measurement surprises you. Most readers return to the table and the mistake list first, and that is the correct order.

## Measurement discipline

Keep a lab notebook entry for every build in this track. The measured values, the deviations from the guide and the reason for each. Six months from now, those notes are worth more than any tutorial. They describe your bench and your components rather than a general case.

When a result here disagrees with your expectation, write down both numbers before changing anything. The gap between predicted and measured is where the real engineering lives. It is usually a tolerance, a parasitic or an assumption that was never checked.
## Formulas and checks from this guide

Verification checklist for this track: watch RSSI before blaming code, measure supply current during radio bursts. Confirm MQTT topics against the broker log. Wireless bugs are usually power or signal problems wearing a software disguise.

Bookmark this page against your next build in the track. The checklist above is the same one used across 23 guides in this series.

## Hard-won notes

Measure current during transmit bursts. Sags under load are power problems, no firmware fixes those.

Location, then device, then measurement. Document the tree before flashing the first device.