myR: ultrasound sensor

The ultrasound sensor is used to measure the distance respect an item in front of it.

A basic ultrasonic sensor consists of one or more ultrasonic transmitters (basically speakers), a receiver, and a control circuit. The transmitters emit a high frequency ultrasonic sound, which bounce off any nearby solid objects. Some of that ultrasonic noise is reflected and detected by the receiver on the sensor.


There are a bounce of tutorial on how to use it.I  just follow this perfect tutorial :

In this post I want to focus the sw code I developed and I just post the wiring:HC_SR04_2

The module is called and it is upload in  Github>>myRover.

Inside you can find an class object called us_sensor_data, that collect the information to share with the world (the distance in [mm] and the period of  measurements in [sec].

This choice to create a separate class will become very useful when I will put all togheter (in the In this way any  object can see all the information from other objects.


The main class  is the us_sensor  object.

def __init__(self, name, trigpin, echopin, data):

Where you need to pass a name, the GPIO pin for the trig signal (output) and the GPIO pin for the echo (input) signal.

This object  works in a parallel thread (threading.thread), so while in your main loop you can do something, the us_sensor continuously (every data.period time) measures the range and put this information in data.distance.

Since it is parallel thread you need to start it first,by calling  mySensor.start(). This call recalls then the run(), where there is the measurement loop.

Then you need to stop it when closing the application , and mySensor.stop().

Note that if you have more threads running  the measurements become less precise.

In addition if an item is very close to the sensor it happens to loose some echo signal.In order to avoid the loop to freeze waiting for a signal that was lost, I manege also a timeout.

Finally you can find a main()  to test the sensor by itsself.

#init data class
data = us_sensor_data()
#init sensor
mySensor = us_sensor('HC_SR04', 4, 17, data)
#from this moment the sensor is measuring and puts the result in
while mySensor.cycling:
     #here do something...
     #than get the info when you need it
     s = 'Distance: ' + str(
# shut down cleanly





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s