<< Summary

Ultrasonic Range Sensor (HC-SR04)
from the Raspberry PI, in Java Raspberry PI

This code is adapted from the Python script available here. This document also explains the way to wire the sensor to the Raspberry PI.

The class 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:

How it works

When a 10 µs signal is sent on the trigger, it causes the module to produce 8 ultrasound bursts at 40 kHz.
Then the echo pin will receive the signal returned by the module when an obstacle is in range.
Knowing how long this signal took to return and knowing the speed of the sound will make the calculation of the distance easy.
For some reasons, the returned signal is sometime lost (or maybe just not received). That is why we use a thread that can be interrupted when the signal takes too long to come back. This way, we don't wait forever.
This turned out to be usefull.
See in rangesensor.HC_SR04andLeds the inner class named TriggerThread.

Note: Grounding the Echo pin with a 1kΩ resistor helps in some cases.

Oliv did it