Using HC-SR04 Ultrasonic Sensor with Raspberry Pi is a relatively easy task. HC-SR04 is a very popular module that can provide the distance to the object by sending ultrasonic bursts at 40kHz and measuring the time it takes for the signal to bounce back. Its interface to any micro-controller platform is very simple and I’ve already done 2 project based on this sensor. One for PIC16F877 and the other for Arduino. Current design as you can probably guess will be based on Raspberry Pi board. The attached Python code sends a short Trigger pulse to HC-SR04 sensor to initiate measuring cycle and waits for Echo signal to return. By measuring Echo time to the target and multiplying it by the sound propagation speed in cm we can get the target distance. In order to match the Raspberry Pi I/O voltage level at 3.3V a basic resistor voltage divider is used as the sensor outputs 5V high logic level as can be seen from design schematic diagram.
The distance is shown on the 2×16 LCD display and on the console if you are using IDLE3 on Raspbian for example. It may be a good idea to add some kind of a measurement time out limit in order to prevent incorrect readings. These invalid readings can be the result of not receiving the Echo signal in correct time frame.