Ultrasonic Sensor

Ultrasonic Sensor Boards

If you connect a cheap 4 pin Ultrasonic Module as per this diagram, then you can safely connect it to your Pi BUT ONLY WITH THE RESISTORS IN PLACE IF USING A 5V OLDER MODEL 

There are two 2K2 and one 1K resistor in this diagram.

Using this arrangement, you only need one spare GPIO pin to trigger it and receive the returned pulse.

So now you simply use it (assuming connected to pin 23)

Use Sonar23 followed by a wait 1 and then just use the sensor item sonar23 to get the distance measured in cm. Any pin can be used for this purpose and if you had several of them you could broadcast each of them in turn.
Alternatively, you can usebroadcast ultra23 which will tell your Raspberry Pi to continuously do a distance check every 1 second and update sensor item ultra23 with the results without any further need to do another broadcast.

If you wish to have it update more quickly, you can define a variable called UltraDelay and make the updating more frequent.  Not recommended to go any faster than 0.1 sec between updates

Update 3rd March 2019

With the advent of the new HC-SR04 that are 3.3V compatible – there is no need for the resistors (AS LONG AS YOU CONNECT IT’S POWER TO PIN1) and its easier to just connect the trigger and echo pins to separate pins on the pi

Therefore to use them like this with trigger connected to pin12 and echo connected to pin13

or using S3GPIO