HC-SR04 guides · On this page

Measure Distance with an HC-SR04 on an ESP32

Measure distance with an HC-SR04 on an ESP32, with nearly the same code as on an Arduino. The HC-SR04 is a 5 V module and its ECHO pin answers at 5 V, more than an ESP32 pin can take, so ECHO reaches the ESP32 through two resistors that bring it down to 3.3 V.

This guide uses an ESP32 DevKitC, the common ESP32-WROOM-32 board. For the sensor itself, see the HC-SR04 guide.

Try it first, no parts needed

This is the whole project on an ESP32, running in your browser. Press Run simulation, then move the target with the slider, or hold the button to bring your hand close, and watch the ESP32 print each distance.

Ready
Open in Cirkit Designer

What the HC-SR04 sees

The sketch takes a reading, then waits 100 ms.

100 cm

ESP32 serial monitor115200 baud

Output appears here when the simulation runs.

What the code does

The sketch is the Arduino one with two pin numbers changed: it starts a reading, times the echo, prints the distance, waits 100 ms and starts again.

hc_sr04_esp32.ino
// Measure distance with an HC-SR04 on an ESP32. ECHO is a
// 5 V signal, so it reaches GPIO 18 through a 1k / 2k divider.
const int TRIG_PIN = 19;
const int ECHO_PIN = 18;

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

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);  // a 10 us pulse starts it
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait up to 30 ms: 400 cm takes about 23 ms.
  unsigned long echoUs = pulseIn(ECHO_PIN, HIGH, 30000);
  if (echoUs == 0) {
    Serial.println("Out of range");
  } else {
    float cm = echoUs / 58.0;  // 58 us of echo per cm
    Serial.print("Distance: ");
    Serial.print(cm, 1);       // one decimal place
    Serial.println(" cm");
  }
  delay(100);  // at least 60 ms between readings
}
  1. const int TRIG_PIN = 19;

    TRIG on GPIO 19. The ESP32's 3.3 V is a HIGH to the module, so TRIG needs nothing in between.

  2. const int ECHO_PIN = 18;

    ECHO on GPIO 18, through the divider. See wire it for why ECHO needs it.

  3. unsigned long echoUs = pulseIn(ECHO_PIN, HIGH, 30000);

    Times ECHO's HIGH in microseconds, or gives 0 if nothing comes back within 30 ms, as on an Arduino.

  4. float cm = echoUs / 58.0;  // 58 us of echo per cm

    Turns the time into centimetres with the datasheet's 58 µs per centimetre.

Build it on an ESP32

Now with real parts. Wire it, get the code, then upload it and watch the distances. Not sure which pin is which? See the HC-SR04 pinout.

You'll need

  • An ESP32 DevKitC (ESP32-WROOM-32) and a USB cable that carries data
  • An HC-SR04
  • A 1 kΩ resistor (brown, black, red bands) and a 2 kΩ resistor (red, black, red)
  • A breadboard and jumper wires
  • Software to upload the sketch: either Cirkit Designer, free in your browser, or the Arduino IDE with Espressif's ESP32 boards installed
  1. Wire it

    VCC, TRIG and GND go straight to the ESP32; ECHO goes through the divider.

    Tap a connection to see it on the circuit.

    HC-SR04 pinConnect to the ESP32Show
    VCC5VShow
    TRIGGPIO 19Show
    ECHO1 kΩ to GPIO 18, and 2 kΩ from GPIO 18 to GNDShow
    GNDGNDShow

    ECHO goes through the divider. An ESP32 pin takes at most 3.6 V, and ECHO answers at 5 V. The 1 kΩ and 2 kΩ share the 5 V, so GPIO 18 sees 5 × 2 ÷ 3 = 3.33 V. TRIG goes straight across: the ESP32 drives it, and its 3.3 V is over the 2 V a 5 V TTL input counts as HIGH.

  2. Get the code

    I'm using:

    Steps 2 and 3 follow the tool you pick.

    Open in Cirkit Designer

    The project opens with the sketch already in it, so there's nothing to install.

    Install the ESP32 boards first, as Espressif's installing guide shows. In Preferences, add https://espressif.github.io/arduino-esp32/package_esp32_index.json to Additional Board Manager URLs; then open Tools → Board → Boards Manager, search for esp32 and install it. The sketch needs no library. Copy it into a new sketch:

    How it works line by line is in what the code does, above.

  3. Upload and check it

    Plug in your ESP32. In Cirkit, open the Build tab, then Upload firmware: click Select Port and pick your board, then Upload to Device. The first time, Cirkit asks you to install Cirkit Create Agent, a small desktop helper that lets it reach the board over USB. Then open Upload output and serial monitor and click Start Serial Monitor.

    Show me where to click in Cirkit
    HC-SR04 on an ESP32FileEditExportHelp
    DesignCodeSimulateBuild
    1Parts & purchasing2Assemble3Upload firmware
    ESP32Edit Code

    Board

    ESP32 Change

    2

    Port

    Select PortCOM4 Connected

    3

    Upload

    Upload to DeviceUploading...Upload successful

    4

    Check that it works

    Your project should now run as designed.

    Upload output and serial monitor
    Compile / Upload Output
    Sketch uses 283215 bytes (21%) of program storage space. Maximum is 1310720 bytes.
    Global variables use 20800 bytes (6%) of dynamic memory, leaving 306880 bytes for local variables. Maximum is 327680 bytes.
    Device SerialStop

    Read serial data from your device.

    Start Serial Monitor
    Listening on COM4 at 115200 baud
    Distance: 100.0 cm
    Distance: 100.1 cm
    Distance: 100.0 cm
    Distance: 25.0 cm
    Distance: 25.0 cm
    Select port

    Select a device port

    Select the device port for uploading code and serial communications

    COM4 (ESP32)
    1. Open Build
    2. Choose Upload firmware
    3. Click Select Port
    4. Pick COM4 (ESP32)
    5. Click Upload to Device
    6. Open Upload output and serial monitor
    7. Click Start Serial Monitor

    In the Arduino IDE, choose ESP32 Dev Module and its port from the board menu, press Upload, then open the Serial Monitor and set it to 115200 baud.

    Show me where to click in the Arduino IDE
    Select BoardESP32 Dev Module

    Select other board and port

    ESP32 Dev ModuleCOM4
    hc_sr04_esp32.ino
    // Measure distance with an HC-SR04 on an ESP32. ECHO is a
    // 5 V signal, so it reaches GPIO 18 through a 1k / 2k divider.
    const int TRIG_PIN = 19;
    const int ECHO_PIN = 18;
    
    void setup() {
    OutputSerial Monitor115200 baud

    Compiling sketch...

    Sketch uses 283215 bytes (21%) of program storage space. Maximum is 1310720 bytes.

    Global variables use 20800 bytes (6%) of dynamic memory, leaving 306880 bytes for local variables. Maximum is 327680 bytes.

    Uploading...

    Distance: 100.0 cm

    Distance: 100.1 cm

    Distance: 100.0 cm

    Distance: 25.0 cm

    Distance: 25.0 cm

    Done uploading.

    1. Click the board menu
    2. Pick ESP32 Dev Module on COM4
    3. Click Upload
    4. Wait for Done uploading
    5. Click Serial Monitor
    6. Check it is set to 115200 baud

    It works when:

    • After a few start-up lines from the ESP32's boot ROM, a new distance appears several times a second, such as Distance: 100.0 cm with something a metre away.
    • You move your hand towards the sensor and the distance drops with it.

    Not working? See troubleshooting.

    Next guideNext: build a parking sensorAn LED that blinks faster as something gets closer, built on an Arduino Uno.

Which ESP32 pins to use

TRIG needs a pin that can be an output; ECHO only needs an input. GPIO 19 and 18 are both fine on a classic ESP32. Avoid the pins below.

AvoidClassic ESP32ESP32-S3
Input onlyGPIO 34 to 39: fine for ECHO, not for TRIGNone
FlashGPIO 6 to 11GPIO 26 to 32, and 33 to 37 on modules with octal flash or octal PSRAM
Boot (strapping)GPIO 0, 2, 5, 12 and 15GPIO 0, 3, 45 and 46
Native USBNoneGPIO 19 and 20, the USB port's D− and D+

Troubleshooting

Find your symptom; the checks under it run from the most common cause down.

It always prints "Out of range"

  • VCC is on 5V, not 3V3. The HC-SR04 needs 5 V.
  • The divider's middle goes to GPIO 18. ECHO to the 1 kΩ, the 1 kΩ's other end to GPIO 18, and the 2 kΩ from there to GND. With the resistors swapped, GPIO 18 sees only 1.67 V, too low to be sure of reading HIGH.
  • TRIG and ECHO aren't swapped. TRIG on GPIO 19, ECHO through the divider to GPIO 18.

More causes are in the HC-SR04 guide's troubleshooting.

Nothing in the Serial Monitor, or garbled characters

  • The Serial Monitor is set to 115200 baud. It must match Serial.begin(115200). The ESP32's own start-up lines come first at the same speed.

No port appears for the ESP32

  • The cable carries data. The board's USB port carries its serial link as well as power, so a cable that only charges powers the board but shows no port.
  • The board's USB-to-serial chip has its driver. Its name, such as CP210x, is printed on the chip near the USB socket. The driver usually installs itself; if no port appears, install it from the chip's maker (Silicon Labs for a CP210x).

The upload stops at Connecting..., then says Failed to connect

  • The board is in download mode. Hold BOOT, press and release EN (RST on some boards), then release BOOT, and upload again.

FAQ

Do I really need the resistors on ECHO?

Yes. ECHO answers at 5 V and an ESP32 pin is rated for at most 3.6 V. The divider brings it to 3.33 V; see wire it.

Can I power the HC-SR04 from 3V3?

No, it needs 5 V. Use the DevKitC's 5V pin, which carries the USB's 5 V.

Does the same code work on an ESP32-S3?

Yes, with TRIG moved. GPIO 19 is the S3's USB D− pin, so put TRIG on another, such as GPIO 4, and set TRIG_PIN to 4. In the Arduino IDE, choose ESP32S3 Dev Module.

Simulating the HC-SR04 on an ESP32 in Cirkit Designer

Cirkit runs your compiled sketch on an emulated ESP32, and its HC-SR04 answers through the real pins, as in the HC-SR04 guide; the divider's 3.33 V reaches GPIO 18 as a HIGH. The ESP32's pulseIn() reads the echo almost exactly, 100.0 cm at 100 cm. Its echo is exact, with no beam, surface, temperature or noise.

References