HC-SR04 is a commonly used module for non-contact distance measurement for distances from 2cm to 400cm. It uses sonar (like bats and dolphins) to measure distance with high accuracy and stable readings. It consists of an ultrasonic transmitter, receiver and control circuit. The transmitter transmits short bursts which gets reflected by target and are picked up by the receiver.
The time difference between transmission and reception of ultrasonic signals is calculated. Using the speed of sound and ‘Speed = Distance/Time‘ equation, the distance between the source and target can be easily calculated.
HC-SR04 ultrasonic distance sensor module has four pins:
- VCC – 5V, input power
- TRIG – Trigger Input
- ECHO – Echo Output
- GND – Ground
- VCC -> 5 volt pin on Pi
- Trig -> Trigger activates the sensor and connect to GIO output pin
- Echo -> Receives the signal, read by GPIO input pin
- GND -> GROUND PIN
Time taken by pulse is actually for to and from travel of ultrasonic signals, while we need only half of this. Therefore time is taken as time/2.
Distance = Speed * Time/2
Speed of sound at sea level = 343 m/s or 34300 cm/s
Thus, Distance = 17150 * Time (unit cm)
For accurate distance readings, the output can be calibrated using a ruler. In the below program a calibration of 0.5 cm is added.
For more detail: Distance Calculation with Ultrasonic Sensor