# HC-SR04 ultrasonic sensor returns 0 or wrong distance

> Fix an HC-SR04 that returns 0 or random distances: wiring, the 5 V echo level on 3.3 V boards, trigger pulse, range and time-out.

Canonical: https://roboticsengineering.in/fix/hc-sr04-returns-zero-or-wrong-distance/ | Published: 2026-11-03 | Updated: 2026-11-03

**A reading of 0 usually means no echo came back, and the cause is wiring, power or range.** The HC-SR04 is a 5 V part, so on a 3.3 V board the echo pin needs a level shifter or divider.

## What the message means

The sensor waits for a 10 microsecond pulse on TRIG, sends a burst and then holds ECHO high for as long as the sound takes to return. You time that pulse and convert it to distance.

## Fix it in this order

1. Check power and ground. The sensor needs 5 V. The Arduino 5 V pin works; a 3.3 V pin does not.
2. Check TRIG and ECHO are on the pins your code uses, and not swapped.
3. Send a clean pulse: set TRIG low, then high for 10 microseconds, then low.
4. Use a time-out on pulseIn() so a missed echo returns quickly instead of blocking.
5. On a 3.3 V ESP32, drop the 5 V ECHO signal to 3.3 V with a divider before it reaches the pin.
6. Respect the range, roughly 2 cm to 4 m. Closer or farther objects give 0 or noise. Soft or angled surfaces reflect poorly.

## A simple reading

Distance in cm is the echo time in microseconds multiplied by 0.0343 and divided by 2. Sound travels about 343 m/s at room temperature.

```
long readCm() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  long us = pulseIn(ECHO, HIGH, 30000);
  if (us == 0) return -1;
  return us * 0.0343 / 2;
}
```

## If you see this, do this

| You see | Do this |
| --- | --- |
| Always 0 | No echo. Check wiring, power and range. |
| Jumpy values | Average several readings and keep the sensor still. |
| Works on Arduino, not on ESP32 | The 5 V echo level or the 5 V supply. |

## Related

[ESP32 LoadProhibited](https://roboticsengineering.in/fix/esp32-guru-meditation-error-loadprohibited/), [voltage divider calculator](https://roboticsengineering.in/led-resistor-voltage-divider-calculator/).

Last reviewed: November 2026. These are the usual causes and the order that finds them fastest. Test on your own board; clones and cables differ.
