All articles

    The HC-SR04 Ultrasonic Sensor: Measuring Distance with Arduino and ESP32

    How the HC-SR04 ultrasonic sensor works, converting echo time to distance, wiring and code, steady readings with a median filter, temperature compensation, project ideas (water tank, parking sensor, obstacle-avoiding robot), using it safely with an ESP32, and troubleshooting.

    Updated 7 min read

    The sensor that looks like a pair of "eyes" is one of the most popular in projects: in robots that avoid walls, parking sensors, and measuring the water level in a tank. And it works just like a bat: it sends out a sound and waits for the echo.

    How does it work?

    1. One "eye" sends a burst of ultrasonic sound (40 kHz).
    2. The sound hits an object and bounces back.
    3. The other "eye" receives it.
    4. The sensor outputs a pulse on the Echo pin whose length = the time the sound took to travel there and back.
    The pulse travels to the wall and back, and that time is converted to distance
    The pulse travels to the wall and back, and that time is converted to distance

    From time to distance

    The speed of sound is about 343 metres per second (at around 20 °C), and the sound covers the distance twice (there and back):

    distance (cm) ≈ time (µs) ÷ 58

    Where does 58 come from?

    343 m/s = 0.0343 cm per microsecond. The sound goes and comes back, so distance = time × 0.0343 ÷ 2 = time × 0.01715, which is the same as time ÷ 58.3. So an Echo pulse 1166 µs long means the object is about 20 cm away.

    Wiring (Arduino Uno)

    SensorArduino
    VCC5V
    Trigpin 9
    Echopin 10
    GNDGND

    The code

    const int TRIG = 9, ECHO = 10;
    
    void setup() {
      Serial.begin(9600);
      pinMode(TRIG, OUTPUT);
      pinMode(ECHO, INPUT);
    }
    
    void loop() {
      digitalWrite(TRIG, LOW);  delayMicroseconds(2);
      digitalWrite(TRIG, HIGH); delayMicroseconds(10);
      digitalWrite(TRIG, LOW);
      long t = pulseIn(ECHO, HIGH, 30000);
      Serial.println(t / 58.0);
      delay(100);
    }

    A 10 µs pulse on Trig starts a measurement, and pulseIn measures the length of the Echo pulse.

    The last argument to pulseIn (30000) is the maximum time to wait, in microseconds. If no echo returns within 30 ms (meaning nothing within about 5 m), the function returns zero. So your code must treat zero as "no reading", not "the object is touching the sensor".

    What happens inside the sensor

    After the Trig pulse, the sensor sends 8 sound pulses in a row at 40 kHz, then raises the Echo pin until the echo returns. So the length of the Echo pulse is exactly the travel time. Leave about 60 ms between measurements so the old echo dies away and doesn't get mixed up with the new one.

    Its limits

    • Range: about 2 cm to 4 m. Closer than that it won't read well.
    • Surfaces: soft surfaces (fabric or foam) absorb sound, and angled surfaces reflect it away. Either way the reading is lost.
    • Field of view is about 15 degrees, so the sensor may see something off to the side.
    • Multiple sensors: if they run at the same time they can hear each other's echoes. Fire them one after another.
    • Temperature changes the speed of sound a little. For high accuracy, compensate for temperature.

    A steady reading: the median, not the average

    Every so often the reading can jump to a strange number (an echo from something to the side, or a zero). An average is affected by that outlier; a median isn't:

    float readCm() {
      float r[5];
      for (int i = 0; i < 5; i++) {
        digitalWrite(TRIG, LOW);  delayMicroseconds(2);
        digitalWrite(TRIG, HIGH); delayMicroseconds(10);
        digitalWrite(TRIG, LOW);
        long t = pulseIn(ECHO, HIGH, 30000);
        r[i] = (t == 0) ? 999 : t / 58.0;   // 999 = no echo
        delay(60);
      }
      // simple sort, then pick the middle value
      for (int i = 0; i < 4; i++)
        for (int j = i + 1; j < 5; j++)
          if (r[j] < r[i]) { float x = r[i]; r[i] = r[j]; r[j] = x; }
      return r[2];
    }

    This measurement takes about a third of a second, which is fine for a tank or a parking sensor. On a robot that needs faster reactions, take 3 readings instead of 5. Note that pulseIn blocks the program until the reading finishes, so if your code does other things at the same time, read the millis instead of delay article.

    Temperature compensation

    The speed of sound increases with temperature roughly like this:

    speed (m/s) ≈ 331.3 + 0.606 × temperature (°C)

    The number 58 assumes about 20 °C. On a 35 °C summer day the speed is about 352.5 m/s instead of 343, so the reading comes out about 3% short: about 5 cm at 2 m. If that accuracy matters, read the temperature with a sensor such as the DS18B20 and calculate:

    distance (cm) = time (µs) × speed ÷ 20000

    Project ideas

    Water level in a tank

    The sensor sits in the tank lid looking down. Level = tank height − measured distance. The problem is that steam and humidity damage an ordinary HC-SR04 over time. For tanks use the waterproof JSN-SR04T (a single transducer in a tube on a cable), with almost the same code, but its minimum distance is about 20 cm, so mount it at least that far above the maximum water level.

    Car parking sensor

    The closer the distance, the faster the buzzer beeps: silent above 100 cm, beeping at shorter intervals from 100 to 30 cm, and a continuous tone below 30. Use an active buzzer to keep the code simple; the difference between types is in the buzzer and speaker article.

    Obstacle-avoiding robot

    The sensor sits on a servo that turns left and right, and the robot drives until it finds something closer than 25 cm, stops, looks left and right, and turns towards the more open side. Driving the motors is in the DC motor and H-bridge article, and the servo in the servo and stepper article.

    With an ESP32

    The standard HC-SR04 needs 5 V, and its Echo pin outputs 5 V, which is more than an ESP32 can tolerate. The solutions:

    • A voltage divider on Echo, for example 1 kΩ and 2 kΩ, giving about 3.3 V.
    • Or use the HC-SR04P or other versions that run on 3.3 V.
    The sensor powered from 5 V, Trig connected directly, and Echo brought down to 3.3 V with two resistors before reaching the ESP32
    The sensor powered from 5 V, Trig connected directly, and Echo brought down to 3.3 V with two resistors before reaching the ESP32

    The Trig pin needs nothing: the sensor reads the ESP32's 3.3 V output as HIGH on most versions. If it doesn't work, try a level shifter.

    Or a different sensor?

    • VL53L0X and VL53L1X: small laser (time-of-flight) sensors over I2C. Accurate with a narrow beam, so they don't pick up things to the side, but their range is shorter and they dislike direct sunlight and shiny black surfaces. How I2C works is in the UART, I2C and SPI article.
    • Sharp infrared sensors: analog output, fast, but the reading depends on the surface colour.
    • The HC-SR04 remains the cheapest and easiest for anything from 5 cm to a few metres, and the object's colour doesn't matter to it.

    Not working?

    • The reading is always zero: usually Trig and Echo are swapped, the sensor isn't getting 5 V, or there's simply nothing in range. Try your hand at 20 cm.
    • The reading is stuck at a small number: something very close to the sensor (a wire or the edge of an enclosure) is reflecting the sound. Move it away, or let the sensor stick out of the enclosure a little.
    • The reading jumps around: take the median as in the code above, and make sure the supply is steady: the sensor draws a current peak while transmitting, and a 100 µF capacitor next to it helps.
    • Works with the Uno but not the ESP32: check the voltage divider on Echo, and the common ground.

    FAQ

    Can it measure the distance to water or a liquid surface? Yes, water reflects sound well as long as it's calm. Waves and foam ruin the reading.

    Can I run several sensors on the same Arduino? Yes, each with its own Trig and Echo, but fire them one after another rather than together so they don't hear each other's echoes.

    Circuits Nerd
    © 2026 Circuits Nerd. All rights reserved.