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.
What the HC-SR04 sees
The sketch takes a reading, then waits 100 ms.
ESP32 serial monitor115200 baud
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.
// 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
}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.
const int ECHO_PIN = 18;ECHO on GPIO 18, through the divider. See wire it for why ECHO needs it.
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.
float cm = echoUs / 58.0; // 58 us of echo per cmTurns 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
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 pin Connect to the ESP32 Show VCC 5V Show TRIG GPIO 19 Show ECHO 1 kΩ to GPIO 18, and 2 kΩ from GPIO 18 to GND Show GND GND Show 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.
Get the code
I'm using:Steps 2 and 3 follow the tool you pick.
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.jsonto 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.
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
Select a device port
Select the device port for uploading code and serial communications
COM4 (ESP32)- Open Build
- Choose Upload firmware
- Click Select Port
- Pick COM4 (ESP32)
- Click Upload to Device
- Open Upload output and serial monitor
- 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
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 baudCompiling 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.
- Click the board menu
- Pick ESP32 Dev Module on COM4
- Click Upload
- Wait for Done uploading
- Click Serial Monitor
- 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 cmwith something a metre away. - You move your hand towards the sensor and the distance drops with it.
Device SerialDistance: 100.0 cmDistance: 100.1 cmDistance: 100.0 cmDistance: 25.0 cmDistance: 25.0 cmOutputSerial MonitorDistance: 100.0 cmDistance: 100.1 cmDistance: 100.0 cmDistance: 25.0 cmDistance: 25.0 cmNot working? See troubleshooting.

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.
| Avoid | Classic ESP32 | ESP32-S3 |
|---|---|---|
| Input only | GPIO 34 to 39: fine for ECHO, not for TRIG | None |
| Flash | GPIO 6 to 11 | GPIO 26 to 32, and 33 to 37 on modules with octal flash or octal PSRAM |
| Boot (strapping) | GPIO 0, 2, 5, 12 and 15 | GPIO 0, 3, 45 and 46 |
| Native USB | None | GPIO 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
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
- HC-SR04 datasheet (ElecFreaks, hosted by SparkFun)
- Espressif ESP32 datasheet (I/O voltage, input-only, flash and strapping pins)
- Espressif ESP32-S3 datasheet (GPIO 19 and 20 as USB D− and D+)
- Arduino-ESP32: installing the ESP32 boards in the Arduino IDE
- Espressif ESP32-DevKitC user guide (its 5V pin, Boot and EN)
- SparkFun: logic levels (a 5 V TTL input's HIGH threshold)
- Arduino: pulseIn()
- ESP-IDF: establishing a serial connection (the USB-to-UART bridge and its driver)
- Espressif esptool: troubleshooting (download mode, the boot log at 115200 baud)
- SparkFun: resistors (the colour code)

