Deciding

if, else, comparisons, and a robot that looks with distance() before it moves.

0.4Python quick startRobot club12 min

Do this lesson in the simulator

So far the robot does the same thing every run. Now it can look before it moves.

The distance sensor

from bugbot import *
connect()

print("the wall ahead is", distance(), "cm away")

Run this in the simulator

distance() gives the centimetres to whatever is straight ahead. Move the robot in the view and run it again.

if and else

from bugbot import *
connect()

gap = distance()
if gap > 30:
    print("plenty of room")
    forward(50, distance=20)
else:
    print("too close")
    backward(50, distance=10)
stop()

Run this in the simulator

if runs the indented lines when the test is true, and else runs its own when it is not. The tests are the ones you would write in maths: >, <, >=, <=, == for "is the same as", != for "is not".

Note ==. One equals sign gives a name to a value; two asks a question.

Stopping at the right moment

Put a test in a while loop and the robot keeps going until it has seen enough.

from bugbot import *
connect()

# drive on while there is more than 15 cm in front
while distance() > 15:
    forward(40)
    wait(0.1)

stop()
print("stopped with", distance(), "cm to spare")

Run this in the simulator

This is the shape of nearly every robot program: look, decide, move, look again.

Task: stop at the wall

Drive up to the wall and stop between 10 cm and 20 cm from it, without touching it. Look as you go, rather than guessing a distance.

from bugbot import *
connect()

while distance() > 40:
    forward(40)
    wait(0.1)

stop()
print("gap", distance())

Challenges

  1. Make the light red when the gap is under 20 cm and green when it is over.
  2. Stop at 15 cm, back off 10 cm, and stop again.
  3. Slow down as you get closer: speed 60 while the gap is over 40, speed 25 after that.