Sending
send(): a broadcast everyone hears; numbers into text.
Do this lesson in the simulatorEvery module so far had one robot on its own. Real robots work in groups: a team in a game, a class on one mat, a robot with a camera helping one without. This module is about how they talk, and it starts with the simplest thing: saying something.
The radio
Every BugBot has a radio. When you call send, the message goes to every other robot on the mat. There is no address and no reply guaranteed: it is a shout, not a phone call. In the classroom the dongle carries it between robots; in the simulator the mat does.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# radio this to every other robot
send("hello")
# pause 0.5 s (the robot keeps doing what it was told)
wait(0.5)
print(messages())
Another robot, the Beacon at the far end of the mat, heard it and answered. messages() is the other half of the radio, and lesson 9.2 is about it. For now: what you send, everyone hears.
The radio log
Under the robot view, the console shows every message anyone sent during the run, in grey, with the time and the sender. Yours as well as theirs. When something goes wrong between two robots, this is where you look.
Messages are text
A message is a string. To send a number you turn it into text first, and an f-string is the neat way:
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# where am I? (cm from where I started)
x, y = position()
send(f"at {x:.0f},{y:.0f}")
print("sent my position")
{x:.0f} prints x with no decimal places: at 0,0, not at 0.0,-0.0. Whoever receives it has to turn the text back into numbers, so keep messages short and regular. Lesson 9.3 is about agreeing that format.
Task: call out
Send hello, drive forward 20 cm, then send your position as at <x>,<y> in whole centimetres from the start.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# radio this to every other robot
send('hello')
# pause 1 s (the robot keeps doing what it was told)
wait(1)
print(messages())
Challenges
- Send your heading as
facing <degrees>. - Send
tick <seconds>once a second for five seconds, usingclock(). - Send your position as JSON (
json.dumps({"x": x, "y": y})), the way lesson 8.7 saved a model.