The HCSR04 is an inexpensive distance sensor. It uses Ultrasonic sound pulses to measure the distance between itself and any obstruction. The HCSR04 consists of two ultrasonic transducers, (one acting as a transmitter and the other as a receiver) and a control circuit. It has 4 pins VCC, GND, TRIG and ECHO. The VCC and GND pins are for powering the sensor, while the TRIG and ECHO are used to detect the distance.
A pulse of at least 10 µS is sent to the TRIG pin, this triggers the transmitter part to send out 8 pulses of ultrasonic sound (at 40KHz). At this time the ECHO pin goes high if the pulses are reflected back by any obstructions and return, the ECHO goes low. The pulse width of the ECHO pin is used to get the time required for the pulse to get back.
Since we know the speed of sound in air, the distance can be calculated by a simple formula: