Lesson 6: The distance sensor
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
The distance sensor
- At the front of the robot is a distance sensor.
front_distance.get_distance(MM)tells you how far the robot is from the wall in front. - On the playground a red dashed line shows each reading.
- With a sensor, one program works even when the walls move.
Words for this lesson
| Word | Meaning |
|---|---|
| sensor | a part that measures something |
| while | repeat while something is true |
| wait | do nothing for a short time: wait(5, MSEC) |
| MSEC | milliseconds; 1000 MSEC = 1 second |
Drive until the wall is close
from vexcode_vr import *
def main():
drivetrain.drive(FORWARD)
while front_distance.get_distance(MM) > 200:
wait(5, MSEC)
drivetrain.stop()
vr_thread(main)
drivetrain.drive(FORWARD)starts driving and does not stop by itself.- The
whileloop keeps checking the sensor. When the wall is 200 mm away or less, the loop ends. drivetrain.stop()stops the wheels.- Check uses several maps: the wall is in a different place on each. Press Map 2 to see one.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Drive towards the wall and stop when it is 100 mm away or less. Do not touch it. The wall is in a different place on each map, so use the sensor and a while loop.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Read the distance once, store it in a variable d, then drive d - 50 mm. The robot should stop about 50 mm from the wall on every map.
Click Run to see the output here.