HC-SR04
ultrasonic distance sensor
Measures distance 2–400 cm with ultrasound, like a bat. One "cylinder" emits a 40 kHz sound, the other listens for the echo.
Open the course →How it works
The ESP32 gives a 10 µs pulse on Trig. The sensor sends 8 ultrasonic pulses and raises Echo HIGH; when the echo returns, Echo falls LOW. The time Echo was HIGH = time for the sound to go there and back. Distance = time × 0.0343 cm/µs / 2. The pulseIn() function measures that time.
Pins and wiring
| Pin | What it is | Where it connects / why |
|---|---|---|
| VCC | 5 V power | → VIN (5 V). At 3.3 V it works unreliably and with shorter range. |
| Trig | Input — start pulse | → GPIO (e.g. 5). Accepts 3.3 V without problems. |
| Echo | Output — pulse whose length = time | → GPIO (e.g. 18) THROUGH A VOLTAGE DIVIDER (1 kΩ + 2 kΩ). Echo gives 5 V and the ESP32 tolerates 3.3 V! |
| GND | Ground | → GND. |
Specifications
Range2 – 400 cm
Accuracy±3 mm
Angle~15°
Power5 V, 15 mA
Frequency40 kHz
Measurement periodmin. 60 ms between measurements
Tips and typical mistakes
- Divider: Echo → 1 kΩ → (to GPIO) → 2 kΩ → GND. Gives 5 × 2/(1+2) = 3.33 V.
- Soft surfaces (fabric, foam) absorb the sound — it returns 0 or huge values.
- There is an HC-SR04+ / 3.3 V version and the RCWL-1601 that work directly at 3.3 V.