Reference
HCSR04
Ultrasonic distance sensor (2-400cm).
- Connects over
- GPIO pins
- Made by
- Cytron / generic
- Datasheet
- cdn.sparkfun.com
Use it
hardware {
device hcsr04: HCSR04(trig: 16, echo: 17)
}
every 1s {
let value: float = hcsr04.distance_cm()
log("hcsr04", "distance_cm={value}")
}
The HCSR04 is wired to ordinary GPIOs: give each of its pins (trig, echo) as a named argument. The compiler checks every pin can do its job.
Methods
-
hcsr04.distance_cm() -> float
Distance in centimeters
Wiring
| Pin | Connect to |
|---|---|
VCC | 5V required |
TRIG | Pulse high ≥ 10 μs to start measurement |
ECHO | 5V output — voltage divide to 3.3V for ESP32/RP2040 |
GND | Ground |
Specifications
- Voltage
- 5V (not 3.3V tolerant — use level shifter on ECHO)
- Current
- 15 mA active
- Range
- 2 cm – 4 m (practical: 5 cm – 2 m)
- Resolution
- ~3 mm at close range
- Beam angle
- ≈ 15°
Tips
- ECHO line is 5V — use a 10kΩ/20kΩ divider before feeding into a 3.3V MCU.
- Distance = (echo_us × 0.0343) / 2 cm (speed of sound at 20°C).
- Reflective surfaces and angles below 30° cause missed echoes.
Alternatives worth knowing:
- VL53L0X: Time-of-flight laser, more accurate, much smaller, 3.3V, but max ~2 m and pricier.
- JSN-SR04T: Waterproof variant if you need outdoor / wet use.