This example uses one sender and at least one receiver micro:bit. Both micro:bit modules can be connected to a single computer, or to separate computers in the same room.
- Start with just two micro:bit modules.
- Open two separate instances of the micro:bit Python Editor.
- If both micro:bit modules are connected to the same computer, they can be two different tabs in the same browser.
- If they are connected to different computers, you will need one micro:bit Python Editor running on each computer.
- If you are in a classroom, pair up with another student and adjust the radio.config(channel=7) statements in both scripts. Make sure that each pair of students is using a unique group number, from 0 to 83.
- Each pair should also update the xor_key from 42 to some value in the 1 to 255 range.
- Connect both micro:bit modules to USB ports.
- With the first micro:bit Python Editor, click Send to micro:bit to flash the Module 1: Sender Encrypted script to one micro:bit module.
- Click Show serial.
- With the second micro:bit Python Editor, Click Send to micro:bit to flash the Module 2: Receiver Encrypted script into one or more micro:bit modules.
- Click Show serial.
Module 1: Sender Encrypted
# Module 1: Sender
import radio
def get_input_string():
print("Enter text:")
return input()
def xor_encrypt(message, key):
encrypted_message = ""
for char in message:
encrypted_message += chr(ord(char) ^ key)
return encrypted_message
# Replace 'YOUR_XOR_KEY' with a value between 0 and 255
xor_key = 42
radio.on()
radio.config(channel=7)
radio.config(length=250)
while True:
user_input = get_input_string()
encrypted_message = xor_encrypt(user_input, xor_key)
radio.send(encrypted_message)
print("Sent:", user_input)
Module 2: Receiver Encrypted
# Module 2: Receiver
import radio
def xor_decrypt(encrypted_message, key):
decrypted_message = ""
for char in encrypted_message:
decrypted_message += chr(ord(char) ^ key)
return decrypted_message
def execute_python_code(script_lines, key):
try:
script = "\n".join(script_lines)
exec(script)
except Exception as e:
print("Error:", e)
# Replace 'YOUR_XOR_KEY' with the same key used in the sender script
xor_key = 42
radio.on()
radio.config(channel=7) # Set the same channel as the sender
radio.config(length=250)
script_lines = []
indent_level = 0
while True:
encrypted_message = radio.receive()
if encrypted_message is not None:
try:
decrypted_message = xor_decrypt(encrypted_message, xor_key)
print("Received:", decrypted_message)
if decrypted_message == "run":
execute_python_code(script_lines, xor_key)
script_lines = []
indent_level = 0
else:
line_indent = len(decrypted_message) - len(decrypted_message.lstrip())
if line_indent > indent_level:
script_lines.append(decrypted_message[indent_level:])
else:
script_lines.append(decrypted_message)
except Exception as e:
print("Error decrypting message:", e)