The HC-SR04 is a $2 component that does something genuinely magical: it measures distance with sound. No optics, no calibration, no protocol — just two pins and a stopwatch.

How it actually works

You pulse the TRIG pin HIGH for 10 microseconds. The sensor then emits an 8-cycle burst of 40 kHz ultrasound. It pulls the ECHO pin HIGH and waits. When the sound bounces off something and returns, the sensor pulls ECHO LOW. The duration ECHO stayed HIGH is the round-trip time of the sound.

Sound travels at about 343 m/s in air. So elapsed_µs × 343 / 1e6 / 2 gives you the one-way distance in metres. The "divide by 2" is because the pulse went there and back. The constant simplification — distance_cm ≈ duration_µs / 58 — is what everyone actually writes.

pulseIn() is the whole sketch

Arduino's pulseIn(ECHO, HIGH) waits for a rising edge, times the pulse, and returns the duration in microseconds. The whole distance read is three lines: pulse TRIG, call pulseIn, divide. Real production code wraps this in a timeout (sound takes ages to come back from far targets) and adds median filtering across a few readings to reject phantom echoes.

What sound can't reach reliably: soft surfaces (couches absorb), narrow targets (less reflective area), angled surfaces (echo reflects away). For self-balancing robots and reverse-parking sensors, it works beautifully. For tracking a bird in flight, find a different sensor.