Wiring the HC-SR04 ultrasonic sensor

Four pins, one pulse and a little maths: how ultrasonic distance measuring works.

The HC-SR04 has four pins: VCC, Trig, Echo and GND. Connect VCC to 5V and GND to ground, then connect Trig and Echo to any two digital pins.

To measure, send a 10 microsecond HIGH pulse on Trig. The module emits a burst of ultrasound and raises Echo for as long as the echo takes to return. Measure that time with pulseIn() and compute distance in centimetres as time in microseconds multiplied by 0.0343, divided by 2.

Tips: the sensor works best on flat, hard surfaces facing it; soft fabric and steep angles reflect poorly. Keep readings above about 2 cm and below about 4 m.