Ultrasonic sensors: measure distance with an echo

The HC-SR04 measures distance as a bat does. One transducer (T) sends a short burst of 40 kHz sound. You cannot hear this frequency. The other transducer (R) listens for the echo. The module makes a pulse on its ECHO pin. The length of this pulse is the time that the sound needs to go to the object and back. The ESP32 measures this time in microseconds and calculates the distance. The range is about 2 cm to 4 m. The standard HC-SR04 needs 5 V, and its ECHO output is also 5 V. You must decrease the ECHO signal to 3.3 V before it goes into the ESP32.

HC-SR04 module: a blue board with two round silver transducers marked T and R, a crystal between them and four pins labeled Vcc, Trig, Echo and GND
HC-SR04. T sends the sound and R receives the echo. The pins are Vcc, Trig, Echo and GND.
Photo: Suyash Dwivedi, CC BY-SA 4.0

Top view: sound pulse and echo

Drag the object. The shaded cone is the ~15° beam. The animation is 100 times slower than real time. A real sensor can make about 16 measurements each second.

The ESP32 sends a 10 µs pulse on TRIG. The module sends 8 cycles of 40 kHz and sets ECHO HIGH. When the echo comes back, ECHO goes LOW. If no echo comes back, ECHO stays HIGH until the module stops waiting (about 38 ms on many boards). The TRIG pulse and the burst are drawn wider than real so that you can see them.

How it works

1 · Trigger

Set TRIG HIGH for at least 10 µs. Then set it LOW. The module then sends a burst of 8 cycles at 40 kHz (200 µs) from the T transducer. A 3.3 V TRIG signal from the ESP32 is high enough for the module.

2 · Echo time

After the burst, the module sets ECHO HIGH. When the R transducer receives the echo, ECHO goes LOW. Measure the HIGH time with pulseIn() or with an interrupt and micros().

3 · Distance

The sound goes to the object and back, so divide by two:
distance = echo time × speed of sound / 2.
At 20 °C, sound travels 343 m/s, which is 0.0343 cm/µs. For example, 1000 µs gives 1000 × 0.0343 / 2 = 17.2 cm.

Speed of sound and temperature

The speed of sound in air is about 331.3 + 0.606 × T m/s (T in °C). It is 325 m/s at −10 °C and 352 m/s at 35 °C. If your code always uses 343 m/s, the error is about 0.18 % for each °C of difference. Outdoors, measure the temperature (for example with a DS18B20 or BMP280) and correct for it.

Beam and range

The datasheet gives a range of 2 cm to 4 m and a measuring angle of about 15°. Real sensors also find large objects a little outside this cone. Below about 2 cm, the module cannot separate the echo from its own burst.

Bad targets

Soft materials (fabric, foam, fur, cushions) absorb the sound. Smooth surfaces at an angle deflect the sound away, as a mirror does with light. In both cases, the echo is lost, or a different object far away gives a wrong, long reading. Small and thin objects (a pencil, a chair leg) send back only a weak echo.

Versions of the sensor

ModuleSupplyECHO levelNotes
HC-SR045 V5 VThe most common version. Use a voltage divider on ECHO. Does not operate reliably at 3.3 V.
HC-SR04P3.0–5.5 VSame as supplyConnect VCC to 3V3. Then ECHO is 3.3 V and needs no divider. Examine the label: some sellers call the 5 V version “HC-SR04P”.
RCWL-16013.0–5.5 VSame as supplySame pins and timing as the HC-SR04. Sold by Adafruit as the “3 V compatible” ultrasonic sensor.
JSN-SR04T / AJ-SR04M5 V (newer boards 3.0–5.5 V)Same as supplyWaterproof transducer on a cable, for tanks and outdoor use. Minimum distance is about 20–25 cm. The beam is wider. Some boards need a TRIG pulse longer than 10 µs; refer to the datasheet of your board.

Wiring

ESP32 5V / VIN GPIO 26 GPIO 27 GND T R HC-SR04 VCC Trig Echo GND 1 kΩ 2 kΩ 5 V echo 3.3 V 5 V supply 3.3 V trigger: OK
The 1 kΩ and 2 kΩ resistors make a voltage divider: 5 V × 2 / (1 + 2) = 3.3 V at GPIO 27. You can also use 10 kΩ and 20 kΩ, or 1 kΩ and two 1 kΩ in series. Read Level shifters for other ways to change 5 V signals to 3.3 V. With an HC-SR04P or RCWL-1601 on 3V3, remove the divider and connect Echo directly.

Connections

HC-SR04 pinConnect toNotes
VCC5V / VINAbout 15 mA. The 5V pin gets USB power. Refer to Power supplies.
TrigGPIO 26Any output pin. Do not use the strapping pins 0, 2, 5, 12, 15.
Echo1 kΩ → GPIO 27, 2 kΩ → GNDThe divider is mandatory for the 5 V HC-SR04. The input-only pins 34–39 are also good for Echo.
GNDGNDCommon ground.
Do not connect a 5 V ECHO pin directly to the ESP32. The GPIO pins are 3.3 V pins and are not 5 V tolerant. A 5 V signal can damage the pin over time. Refer to GPIO.

Build steps

  1. Make the dividerPut the 1 kΩ and 2 kΩ resistors on the breadboard. Measure the voltage at the middle point with 5 V on the top end. Make sure that it is near 3.3 V.
  2. Connect the moduleConnect VCC, GND, Trig and Echo as shown in the table.
  3. Upload sketch 1Open the Serial Monitor at 115200 baud.
  4. Test with a flat targetHold a book 20 cm in front of the sensor. Compare the reading with a ruler.
  5. Attach the sensorPoint it at the area to monitor. Keep it away from walls and table edges that are near the beam.

Troubleshooting

  • The reading is always 0 or “No echo”: VCC is not 5 V, Trig and Echo are swapped, or the target is soft, angled or out of range.
  • Random large readings: an echo from an earlier ping, or from a far wall. Wait 60 ms or more between pings. Use a median filter (sketch 2).
  • The reading is always too short: a table edge or a wall near the beam reflects the sound. Lift the sensor or move it forward.
  • Two sensors give wrong readings: each sensor hears the other sensor. Trigger them one after the other.
  • Errors of some percent outdoors: correct for the air temperature.

Code

These sketches use no library. pulseIn() is part of the Arduino-ESP32 core. Install the core as shown in IDE setup.

1 · Basic distance with pulseIn()

ultrasonic_basic.ino


              const int TRIG_PIN = 26;
              const int ECHO_PIN = 27;                 // through the 1 kΩ / 2 kΩ divider
              const float SOUND_M_PER_S = 343.0;       // speed of sound at 20 °C
              const unsigned long TIMEOUT_US = 30000;  // 30 ms: about 5 m, then pulseIn() returns 0

              void setup() {
                Serial.begin(115200);
                pinMode(TRIG_PIN, OUTPUT);
                digitalWrite(TRIG_PIN, LOW);
                pinMode(ECHO_PIN, INPUT);
              }

              // Returns the distance in cm, or -1 if no echo came back.
              float readDistanceCm() {
                digitalWrite(TRIG_PIN, LOW);
                delayMicroseconds(2);
                digitalWrite(TRIG_PIN, HIGH);
                delayMicroseconds(10);                 // 10 µs trigger pulse
                digitalWrite(TRIG_PIN, LOW);

                unsigned long us = pulseIn(ECHO_PIN, HIGH, TIMEOUT_US);
                if (us == 0) return -1;                // timeout: no echo
                return us * (SOUND_M_PER_S * 100.0 / 1000000.0) / 2.0;   // there and back
              }

              void loop() {
                float cm = readDistanceCm();
                if (cm < 0) Serial.println("No echo");
                else        Serial.printf("%.1f cm\n", cm);
                delay(60);                             // let old echoes die out
              }
            

2 · Temperature correction + median filter

The median of five readings removes single bad readings. Replace airTempC with a value from a temperature sensor.

ultrasonic_median.ino


              const int TRIG_PIN = 26;
              const int ECHO_PIN = 27;
              float airTempC = 20.0;                   // read this from a sensor if you can

              float speedOfSound(float tempC) {        // m/s
                return 331.3 + 0.606 * tempC;
              }

              float readOnceCm() {
                digitalWrite(TRIG_PIN, HIGH);
                delayMicroseconds(10);
                digitalWrite(TRIG_PIN, LOW);
                unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000);
                if (us == 0) return -1;
                return us * speedOfSound(airTempC) / 20000.0;   // µs × m/s → cm, divided by 2
              }

              float readMedianCm() {
                float v[5];
                int n = 0;
                for (int i = 0; i < 5; i++) {
                  float cm = readOnceCm();
                  if (cm > 0) v[n++] = cm;               // keep only good readings
                  delay(60);
                }
                if (n == 0) return -1;
                for (int i = 1; i < n; i++) {            // insertion sort
                  float k = v[i];
                  int j = i - 1;
                  while (j >= 0 && v[j] > k) { v[j + 1] = v[j]; j--; }
                  v[j + 1] = k;
                }
                return v[n / 2];
              }

              void setup() {
                Serial.begin(115200);
                pinMode(TRIG_PIN, OUTPUT);
                digitalWrite(TRIG_PIN, LOW);
                pinMode(ECHO_PIN, INPUT);
              }

              void loop() {
                float cm = readMedianCm();
                if (cm < 0) Serial.println("No echo");
                else        Serial.printf("%.1f cm (at %.0f °C)\n", cm, airTempC);
              }
            

3 · Non-blocking: measure ECHO with an interrupt

pulseIn() stops the program for up to 30 ms. This sketch measures the pulse in an interrupt, so loop() can do other work, for example update an OLED display or a web page.

ultrasonic_interrupt.ino


            const int TRIG_PIN = 26;
            const int ECHO_PIN = 27;
            const uint32_t PING_INTERVAL_MS = 60;

            volatile uint32_t riseUs = 0;
            volatile uint32_t widthUs = 0;
            volatile bool newReading = false;

            void IRAM_ATTR onEcho() {
              uint32_t now = micros();
              if (digitalRead(ECHO_PIN) == HIGH) {
                riseUs = now;                          // ECHO went HIGH: start
              } else {
                widthUs = now - riseUs;                // ECHO went LOW: stop
                newReading = true;
              }
            }

            void setup() {
              Serial.begin(115200);
              pinMode(TRIG_PIN, OUTPUT);
              digitalWrite(TRIG_PIN, LOW);
              pinMode(ECHO_PIN, INPUT);
              attachInterrupt(digitalPinToInterrupt(ECHO_PIN), onEcho, CHANGE);
            }

            void loop() {
              static uint32_t lastPingMs = 0;
              if (millis() - lastPingMs >= PING_INTERVAL_MS) {
                lastPingMs = millis();
                digitalWrite(TRIG_PIN, HIGH);
                delayMicroseconds(10);
                digitalWrite(TRIG_PIN, LOW);
              }

              if (newReading) {
                noInterrupts();                        // make a safe copy
                uint32_t w = widthUs;
                newReading = false;
                interrupts();
                if (w < 25000) Serial.printf("%.1f cm\n", w * 0.0343 / 2.0);
                else           Serial.println("No echo");
              }

              // Do other work here. Do not use long delay() calls.
            }
          

Resources