Listening
messages(): what arrived since you last asked, and who sent it.
Do this lesson in the simulatorPrint it: worksheet (PDF) · answers (PDF) · as a web page
messages() returns everything that arrived since you last asked, oldest first. Each message is a pair: who sent it, and what they said.
They queue up
The Beacon on this mat sends tick <n> once a second. Wait a while before asking, and they are all there waiting for you:
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# pause 3.2 s (the robot keeps doing what it was told)
wait(3.2)
for sender, text in messages():
print(sender, "said:", text)
for sender, text in messages() unpacks each pair into two names as it goes. Four ticks, sent at 0.1, 1.1, 2.1 and 3.1 s and delivered together, because nobody asked for them sooner. The radio does not lose what you do not read straight away; it keeps it until you do.
Ask often
To act on a message when it arrives, ask in a loop, with a short wait:
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# do this 50 times (tick counts from 0)
for tick in range(50):
for sender, text in messages():
print(f"{clock():.1f} s: {sender} said {text}")
# pause 0.1 s (the robot keeps doing what it was told)
wait(0.1)
Now each tick is printed within a tenth of a second of being sent. This shape, check, act, wait, is called polling, and it is how every robot in this module listens. The wait matters: without it the loop asks thousands of times a second and the robot has no time for anything else.
Whose message?
Everyone hears everything, so on a busy mat the sender matters. Ignore what is not for you:
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# do this 30 times (tick counts from 0)
for tick in range(30):
for sender, text in messages():
if sender == "Beacon":
print("beacon:", text)
else:
print("ignoring", sender)
# pause 0.1 s (the robot keeps doing what it was told)
wait(0.1)
Task: listen
Print heard <sender>: <text> for each of the Beacon's messages, at least five of them. Do not drive.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# pause 2 s (the robot keeps doing what it was told)
wait(2)
print(messages())
Challenges
- Count the ticks and print the total at the end.
- Print the time between one tick and the next, using
clock(). - Stop listening as soon as
tick 5arrives.