The answersDownload the PDF
Worksheet

2.2 The distance sensor

Sensing · Robot club · about 15 min

BugBotLab
NameClassDate

What this lesson is about

distance() and loops that react to it.

Questions 7 marks in all

  1. [1 mark]How does the time-of-flight sensor measure distance?

    1. AIt fires invisible light and times how long the reflection takes to come back
    2. BIt counts how far the robot has driven
    3. CIt listens for an echo of a sound
    4. DIt looks at how big things appear in the camera
  2. [1 mark]distance() reads 70 cm. The robot runs forward(60, distance=20) towards the wall. About what does distance() read now? Give a whole number.

  3. [1 mark]This loop stops the robot. Where does it end up?

    while distance() > 30:
        forward(40)
        wait(0.1)
    stop()
    1. AA little closer than 30 cm, because it coasts after stop()
    2. BExactly 30 cm from the wall
    3. CA little further than 30 cm
    4. DTouching the wall
  4. [1 mark]Why is there a wait(0.1) inside the loop? Choose all that apply.

    Tick every answer that is true.

    1. AIt gives the robot time to move before the next look
    2. BIt keeps the safety timer fed
    3. CIt makes the sensor read in millimetres
    4. DIt makes the robot drive at a lower speed
  5. [1 mark]In a "drive until the wall is close" loop, how does the program know how far the wall is?

    1. AIt does not; it asks the sensor before every repeat
    2. BYou type the distance in at the top
    3. CIt works it out from the speed
    4. DIt counts how many loops have run
  6. [1 mark]What does this program print?

    for d in [80, 45, 30]:
        if d > 40:
            print(d, "fast")
        else:
            print(d, "slow")
  7. [1 mark]What does this program print?

    readings = [60, 52, 44]
    for i in range(3):
        print(f"step {i}: wall in {readings[i]} cm")

The task: stop before the wall

Drive up to the wall and stop in the green band in front of it, without touching it. Adjust the number and the speed until the robot stops inside the band every time.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

# as long as the thing ahead is further than 30 cm
while distance() > 30:
    # drive forward at 50 (keeps going until the next command)
    forward(50)
    # pause 0.1 s (the robot keeps doing what it was told)
    wait(0.1)
# all motors off
stop()

Plan your program here, then type it in and press Run.

QR code
Do it on the robot
www.bugbotlab.com/learn/2-2-the-distance-sensor/
The simulator checks it and tells you when it passes. Nothing to install, no account.

Challenges

  1. Stop within 10 cm of the wall at the fastest speed you can manage.
  2. Drive to the wall, turn 180, drive to the other wall, and print both distances.
  3. Make the LED change from green to orange to red as the wall gets closer.