This is a firefly:
It’s a sort of bug that uses bioluminescence to signal (without wires) to its friends. Here’s what they look like when they signal to each other:
The BBC have rather a beautiful video of fireflies available online.
We’re going to use the radio module to create something akin to a swarm of fireflies signalling to each other.
First import radio
to make the functions available to your Python program. At this point the radio module is configured to sensible defaults that make it compatible with other platforms that may target the BBC micro:bit. It is possible to control many of the features discussed above (such as channel and addressing) as well as the amount of power used to broadcast messages and the amount of RAM the incoming message queue will take up. The API documentation contains all the information you need to configure the radio to your needs.
Assuming we’re happy with the defaults, the simplest way to send a message is like this:
radio.send("a message")
The example uses the send
function to simply broadcast the string “a message”. To receive a message is even easier:
new_message = radio.receive()
As messages are received they are put on a message queue. The receive
function returns the oldest message from the queue as a string, making space for a new incoming message. If the message queue fills up, then new incoming messages are ignored.
That’s really all there is to it! (Although the radio module is also powerful enough that you can send any arbitrary type of data, not just strings. See the API documentation for how this works.)
Armed with this knowledge, it’s simple to make micro:bit fireflies like this:
The important stuff happens in the event loop. First, it checks if button A was pressed and, if it was, uses the radio to send the message “flash”. Then it reads any messages from the message queue with radio.receive()
. If there is a message it sleeps a short, random period of time (to make the display more interesting) and uses display.show()
to animate a firefly flash. Finally, to make things a bit exciting, it chooses a random number so that it has a 1 in 10 chance of re-broadcasting the “flash” message to anyone else (this is how it’s possible to sustain the firefly display among several devices). If it decides to re-broadcast then it waits for half a second (so the display from the initial flash message has chance to die down) before sending the “flash” signal again. Because this code is enclosed within a while True
block, it loops back to the beginning of the event loop and repeats this process forever.
The end result (using a group of micro:bits) should look something like this: