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.

Distance Sensor

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:

Pybricks also has two functions to work with the inbuild lights:

Distance Sensor Example

Use the code below to understand how the functions work.

  1. Create a new file called distance_sensor.py

  2. Type the code below into the file

  3. Predict what you think will happen.

  4. Run your code:

 1# distance_sensor.py
 2
 3from pybricks.hubs import PrimeHub
 4from pybricks.pupdevices import Motor, ColorSensor, UltrasonicSensor, ForceSensor
 5from pybricks.parameters import Button, Color, Direction, Port, Side, Stop
 6from pybricks.robotics import DriveBase
 7from pybricks.tools import wait, StopWatch
 8
 9# --- SETUP
10hub = PrimeHub()
11distance_sensor = UltrasonicSensor(Port.C)
12
13# --- MAIN LOOP
14while True:
15    distance = distance_sensor.distance()
16    present = distance_sensor.presence()
17
18    print("Distance:", distance, "\tDetected other sensor:", present)
19
20    distance_sensor.lights.off()
21    wait(100)
22    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 around

  • line 18 → print the values in distance and present

  • 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?