Lesson 6: The distance sensor
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.
In the exam
Past paper 0478/12/F/M/24 Q6(b)(i): a self-driving tractor must stop if a person is within 3 metres. Explain how an infra-red sensor, a microprocessor and an actuator do this. It is your while loop:
- The infra-red sensor keeps measuring the distance to anything in front and sends the data to the microprocessor.
- The microprocessor compares the distance with the stored value (3 m).
- If the distance is 3 m or less, it sends a signal to the actuator (the brakes or the motor) to stop the tractor.
- Otherwise the tractor carries on, and the checks repeat.
Past paper 0478/22/F/M/24 Q6: describe two types of iteration (loop).
- Count-controlled: the number of times is fixed before the loop starts, like
for i in range(4)in lesson 3. - Pre-condition: the condition is checked at the start of each loop, so the loop may not run at all. Your
whileloop is one: if the wall is already close, the loop body never runs and the robot stops at once. - Post-condition: the condition is checked at the end, so the loop always runs at least once (REPEAT … UNTIL in pseudocode; Python has no loop like this).
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
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.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
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.
Nhấn Chạy để xem kết quả ở đây.