This code is adapted from the Python script available here. This document also explains the way to wire the sensor to the Raspberry PI.
rangesensor.HC_SR04andLeds proposes a multi-threaded version of the
rangesensor.HC_SR04. This class is also able to interact with 5 leds. When no led is on, it means there is no obstacle in a range of 50 cm. When all the leds are on, it means there is an obstacle at less than 10 cm. One led will turn on for each chunk of 10 cm.
Beside the power pins, the HC-SR04 has two other pins:
rangesensor.HC_SR04andLedsthe inner class named
Note: Grounding the Echo pin with a 1kΩ resistor helps in some cases.