Taking turns
One robot at a time through a corridor: announce, wait, go.
Do this lesson in the simulatorTwo robots, one corridor wide enough for one. Nobody is in charge. The Porter drives through the corridor on a loop and announces itself: corridor busy as it enters, corridor clear as it leaves. Your job is to get through without touching it. This is a shared resource, and the radio is how robots share one.
Listen to the rhythm
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# do this 160 times (tick counts from 0)
for tick in range(160):
for sender, text in messages():
print(f"{clock():.1f} s: {sender} says {text}")
# pause 0.1 s (the robot keeps doing what it was told)
wait(0.1)
Busy for about five seconds, clear for about nine, round and round. The corridor is 40 cm long and you have 72 cm to cover to reach the far zone, six seconds at speed 60. So the moment you hear clear, there is time, but only if you go straight away.
Wait, announce, go
Three states: waiting for clear, going, done. Announce yourself when you go, entering, and again when you are through. The Porter does not listen (it is a simple robot), but a robot that did could hold back for you, and that is the whole idea of a protocol: it is the agreement, not the hardware.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
clear = False
while not clear:
for sender, text in messages():
if "clear" in text:
clear = True
# pause 0.1 s (the robot keeps doing what it was told)
wait(0.1)
print(f"clear at {clock():.1f} s, going")
# radio this to every other robot
send("entering")
# drive forward at 60 for 20 cm, then stop
forward(60, distance=20)
print("in the corridor at", position())
Straight down the middle
The corridor gives 3 cm each side of the robot, and the robot leaks sideways a little as it drives. Hold the middle by steering from y, the way Module 3 held a lane:
x, y = position()
drive(60, y * 6, wrapped(90 - heading()) * 3)
The robot faces along x (heading 90), so a sideways command pushes it in y, and y * 6 pushes it back to the centre line. The last term holds the heading.
Task: one at a time
Wait for corridor clear, send entering, drive through to the green zone without touching the walls or the Porter.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# radio this to every other robot
send('entering')
# drive forward at 60 for 72 cm, then stop
forward(60, distance=72)
# radio this to every other robot
send('out')
Challenges
- Print how long you waited.
- Send
outwhen you reach the zone, then come back through the corridor the same way. - If
busyarrives while you are still waiting, printmissed itand keep waiting for the nextclear.