If you’ve ever wondered how a parking-assist sensor or a soap dispenser knows something is near it, the answer is usually the same decades-old trick: send out a pulse of sound too high to hear, and time how long it takes to bounce back. The HC-SR04 packages that trick into a two-dollar module, and it’s still one of the most reliable ways to add proximity or distance sensing to an interactive piece without reaching for a camera or a more expensive time-of-flight sensor.
How it actually works
The HC-SR04 has two round “eyes”: one is an ultrasonic transmitter, the other a receiver. You trigger it with a short digital pulse, it emits a burst of 40kHz sound (well above human hearing), and it holds a response pin high for exactly as long as it takes the echo to return. Multiply that time by the speed of sound, divide by two (since the pulse travels to the object and back), and you have distance. There’s no analog voltage to interpret and no calibration curve to fight — just a timed pulse width.
Wiring it up
The module has four pins: VCC (5V), GND, TRIG, and ECHO. On a typical Arduino or ESP32 setup, TRIG and ECHO connect to any two digital pins. One wrinkle worth knowing: the ECHO pin outputs at the sensor’s supply voltage, so on a 3.3V board like most ESP32 boards, you’ll want a simple voltage divider (two resistors) between ECHO and the microcontroller’s input pin to avoid feeding 5V into a 3.3V-rated GPIO.
The code
The standard pattern is: pull TRIG low, wait a couple of microseconds, pulse it high for 10 microseconds, then measure how long ECHO stays high with pulseIn(). That duration, converted to centimeters, is your distance reading. Most beginner tutorials wrap this in a simple loop that prints the distance every few hundred milliseconds — enough for triggering an installation response (someone’s within a meter, start the animation) without needing frame-rate precision.
Where it falls short
The HC-SR04 has real limits worth knowing before you build around it. It struggles with soft, sound-absorbing materials (fabric, foam) that don’t reflect the pulse cleanly, and with angled surfaces that deflect the echo away from the receiver instead of back to it. Its beam is also fairly wide, so it’s better at “is something generally in this zone” than precise single-point distance measurement. For narrower-beam precision, or for materials that absorb ultrasound poorly, a laser time-of-flight sensor like the VL53L1X is the usual upgrade — at several times the cost.
When it’s still the right choice
For most installation-triggering use cases — “wake up when a visitor approaches,” “measure roughly how close someone is standing,” “detect an object entering a zone” — the HC-SR04’s cheapness and simplicity make it hard to beat. It needs no library beyond what’s built into pulseIn(), no calibration, and it’s been a known quantity in the hobbyist world for long enough that almost every problem you’ll hit already has a documented answer.