HC-SR04 ultrasonic distance with ESP32
Supply 5 V
Bus GPIO
Measures distance
Pins and ESP32 wiring
| Pin | Role | ESP32 pin | Notes |
|---|---|---|---|
| VCC | Power | VIN | Needs 5 V: use VIN |
| TRIG | Input (the ESP32 drives it) | D25 | A 10 µs HIGH pulse starts a measurement |
| ECHO | Output (the part drives it) | D26 | Outputs 5 V: use a voltage divider (e.g. 1 kΩ + 2 kΩ) before the ESP32 pin |
| GND | Ground | GND |
Suggested wiring for the 30-pin ESP32 DevKit, avoiding flash, input-only and strapping pins. BoardPilot checks it for you as you wire.
This module is sold for 5 V. Its outputs may be 5 V: use a level shifter or a voltage divider on ESP32 inputs.
Good to know
- on 3.3 V boards: ECHO outputs 5 V. On a 3.3 V board, put a voltage divider (for example 1 kΩ and 2 kΩ) between ECHO and the pin. (Cytron / ElecFreaks HC-SR04 user manual, Electric parameters: working voltage DC 5 V)
- It needs 5 V on VCC. At 3.3 V most modules give no echo or wrong distances. (Cytron / ElecFreaks HC-SR04 user manual, Electric parameters: working voltage DC 5 V)
- Leave at least 60 ms between measurements, or the echo of the last one is measured again. (Cytron / ElecFreaks HC-SR04 user manual, Timing diagram: measurement cycle over 60 ms)
Sources
- Cytron / ElecFreaks HC-SR04 user manual, Pins VCC, Trig, Echo, GND; 10 µs trigger pulse; 5 V supply
Try it in 3D in BoardPilot
HC-SR04 ultrasonic distance on other boards: wiring and code
Arduino Mega 2560 R3 Arduino Nano Arduino Uno R3 WeAct Black Pill STM32F411CE ESP32-C3-DevKitM-1 ESP32-S3-DevKitC-1 Nordic nRF52840 DK NUCLEO-F401RE Raspberry Pi Pico 2 Raspberry Pi Pico W Raspberry Pi Pico Teensy 4.1
Learn the basics
Lesson: GPIO: pins in and out Lesson: Hardware basics for software developers GPIO Level shifter Logic level (HIGH and LOW)
Related parts
A02YYUW waterproof ultrasonic distance (UART)A3144 hall effect switchAM312 mini PIR motion sensorATGM336H GPS/BeiDou moduleBeitian BN-220 GPS moduleBenewake TF-Luna LiDAR (UART mode)
Part data: CC BY 4.0, free to reuse with credit to BoardPilot.