Distance Sensor¶
Pybrick Documentation
To explore all Pybricks’ features check the Pybricks documentaion. This can also be seen in the right-hand panel of the Pybricks IDE.
The Distance Sensor measures distance to an object or surface using ultrasound. The sensor works by sending out high frequency sound waves that bounce off any object in range, and measuring how long it takes the sound to return to the sensor. The Distance Sensor can also be used as a light source, with four LED segments around the “eyes” that can be controlled individually.
To initialise the distance sensor you must call the UltrasonicSensor()
class and nominate it’s port. For example, with the robot you would use:
distance_sensor = UltrasonicSensor(Port.C)
Distance Sensor Functions¶
There are two functions you can use to get readings from the distance sensor:
distance()→ int: mm
→ Measures the distance (mm) between the sensor and an object using ultrasonic sound waves.presence()→ bool
→ Checks for the presence of other ultrasonic sensors by detecting ultrasonic sounds.
Pybricks also has two functions to work with the inbuild lights:
lights.on(brightness)
→ Turns on the lights at the specified brightness.lights.off()
→ Turns off all the lights.
Distance Sensor Example¶
Use the code below to understand how the functions work.
Create a new file called
distance_sensor.py
Type the code below into the file
Predict what you think will happen.
Run your code:
1from pybricks.hubs import PrimeHub
2from pybricks.pupdevices import Motor, ColorSensor, UltrasonicSensor, ForceSensor
3from pybricks.parameters import Button, Color, Direction, Port, Side, Stop
4from pybricks.robotics import DriveBase
5from pybricks.tools import wait, StopWatch
6
7# --- SETUP
8# start components
9hub = PrimeHub()
10distance_sensor = UltrasonicSensor(Port.C)
11
12# store variables
13
14# --- RUNNING
15while True:
16 # read sensor data
17 distance = distance_sensor.distance()
18 present = distance_sensor.presence()
19
20 # process data
21
22 # output data
23 print("Distance:", distance, "\tDetected other sensor:", present)
24
25 distance_sensor.lights.off()
26 wait(100)
27 distance_sensor.lights.on(100)
Investigate
lines 3 - 7 → imports all the Pybricks command for use with your robot
line 10 → initialises the hub
line 11 → initialises the distance sensor
line 14 → create main loop
line 15 → get a distance reading from the sensor and store in
distance
line 16 → store in
present
if there are any other ultrasonic sensors aroundline 18 → print the values in
distance
andpresent
line 20 → turn lights off
line 21 → wait 100 milliseconds
line 22 → turn lights on to 100%
Modify
what happens when your comment out line 21?
what is the maximum distance reading?
what is the minimum distance reading?