In air, sound travels at a speed of 343 metres per second. An ultrasonic distance sensor sends out pulses of ultrasound which are inaudible to humans, and detects the echo that is sent back when the sound bounces off a nearby object. It then uses the speed of sound to calculate the distance from the object.
We will assume that you have your raspberry pi setup and ready to go. If you need help with this visit our blog
What I used
- HC-SR04 Ultrasonic Sensor Distance Measuring Module
- Breadboard Jumper Cable
- 830 Point Solderless Breadboard
from gpiozero import DistanceSensor
ultrasonic = DistanceSensor(echo=17, trigger=4)
As well as being able to see the distance value, you can also get the sensor to do things when the object is in or out of a certain range.
Use a loop to print different messages when the sensor is in range or out of range:
print("Out of range")
Now wave your hand in front of the sensor; it should switch between showing the message “In range” and “Out of range” as your hand gets closer and further away from the sensor. See if you can work out the point at which it changes.
The default range threshold is 0.3m. This can be configured when the sensor is initiated:
ultrasonic = DistanceSensor(echo=17, trigger=4, threshold_distance=0.5)
Alternatively, this can be changed after the sensor is created, by setting the threshold_distance property:
ultrasonic.threshold_distance = 0.5
Try the previous loop again and observe the new range threshold.
The wait_for functions are blocking, which means they halt the program until they are triggered. Another way of doing something when the sensor goes in and out of range is to use when properties, which can be used to trigger actions in the background while other things are happening in the code.
First, you need to create a function for what you want to happen when the sensor is in range:
Then set ultrasonic.when_in_range to the name of this function:
ultrasonic.when_in_range = hello
Add another function for when the sensor goes out of range:
ultrasonic.when_out_of_range = bye
Now these triggers are set up, you’ll see “hello” printed when your hand is in range, and “bye” when it’s out of range.
You may have noticed that the sensor distance stopped at 1 metre. This is the default maximum and can also be configured on setup:
ultrasonic = DistanceSensor(echo=17, trigger=4, max_distance=2)
Or after setup:
ultrasonic.max_distance = 2