HC-SR04 ultrasonic sensor
Measures distance with sound. A short pulse on TRIG makes the module emit an ultrasound burst; ECHO stays high for the round-trip time of the echo. Distance in cm = ECHO time in µs ÷ 58. Careful: it is powered with 5 V and ECHO comes out at 5 V — run it through a voltage divider before the ESP32 pin.
Pinout
| Pin | Connect to | Note |
|---|---|---|
| VCC | VIN (5 V) | |
| TRIG | output GPIO (e.g. 25) | a 10 µs pulse triggers the measurement |
| ECHO | input GPIO (e.g. 18) through a voltage divider | 5 V! never directly on the pin |
| GND | GND | the same GND as the ESP32 |
FastMindLocal AI assistant
The AI that remembers your life and lives on your computer
- Long-term memory with the source of every answer
- Works offline: your data stays on your PC
- Reads PDFs, slides, photos and meeting recordings
Essential plan free forever
MicroPython example
import machine
from machine import Pin
import time
trig = Pin(25, Pin.OUT, value=0)
echo = Pin(18, Pin.IN) # ECHO is 5 V: use a voltage divider!
def medir_cm():
trig.value(1)
time.sleep_us(10) # 10 µs pulse on TRIG
trig.value(0)
pulso = machine.time_pulse_us(echo, 1, 30000) # µs with ECHO at 1
if pulso < 0:
return None # no echo within 30 ms
return pulso / 58
while True:
d = medir_cm()
if d is None:
print("no echo")
else:
print("%.1f cm" % d)
time.sleep(0.5)
Specifications
| Item | Value | Source |
|---|---|---|
| Power supply | 5 V (VIN) | Typical datasheet values |
| Trigger (TRIG) | pulse ≥ 10 µs | Typical datasheet values |
| Response (ECHO) | high for distance (cm) × 58 µs | Typical datasheet values |
| Range | 2–400 cm | Typical datasheet values |
| No echo | ECHO high for ≈ 38 ms | Typical datasheet values |
| ECHO level | 5 V: triggers the "5 V on a 3.3 V pin" warning | Typical datasheet values — Under review: divider values used in the lab |
| Variant | the HC-SR04P works at 3.3 V | Typical datasheet values |
| TRIG → ECHO delay | the simulator uses 0 | PyPlaca component catalog — Under review: measure on the module |
Values marked "Under review" will still be checked against the parts in the lab.