HC-SR04 ultrasonic sensor returns 0 or wrong distance

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 seeDo this
Always 0No echo. Check wiring, power and range.
Jumpy valuesAverage several readings and keep the sensor still.
Works on Arduino, not on ESP32The 5 V echo level or the 5 V supply.

ESP32 LoadProhibited, 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.