How the Sender, Receiver, and Sniffer Work

The transmitter script broadcasts a string containing a term every 2.5 seconds.  Those terms HAPPY, SAD, ANGRY can be used by receivers in statements that work the same way as display.show(Image.HAPPY), display.show(Image.SAD), and so on.

 

Transmitter Script

The statements below set up and turn on the micro:bit module’s built-in radio and also provide a helpful 1-second delay before sending data to the terminal.  To find out more, try out the Cybersecurity: Radio Basics activities.

# radio_send_images.py

from microbit import *
import radio

radio.on()
radio.config(channel=7)

sleep(1000)

 

A convenient approach to sending predefined image data through the radio is to simply send strings that contain words like "HAPPY", "SAD", "ANGRY" that can be used as arguments. The receiver script can build a statement like display.show(Image.HAPPY).  In addition to sending the data packet, the transmitter script prints the word on the terminal so you can monitor which mood/reaction image it’s sending through radio.send(packet).  

while True:

    packet = "HAPPY"
    print("Send:", packet)
    radio.send(packet)
    sleep(2500)

    ...

 

Receiver Script

After the same familiar initialization, the receiver script's main loop checks for incoming messages with packet = radio.receive().  If nothing is received, packet = None, and the statements under if packet: get skipped.  When packet stores a string like "HAPPY", "SAD", or "ANGRY", the statements indented below if packet: print the string to the terminal, and then display the corresponding image on the micro:bit module’s LEDs matrix.  

while True:
    
    packet = radio.receive()

    if packet:
        print("Receive:", packet)
        display.show(getattr(Image, packet))

 

The trick to using a string to access the image is to use getattr (object, name).  This “get attribute” function accepts an object and the string name of one of its properties.  It responds by returning that property.  When packet contains "HAPPY", then getattr(Image, "HAPPY") returns Image.HAPPY, and the micro:bit lights up its LEDs in response to display.show(Image.HAPPY).