Search code examples
pythonbbc-microbit

module radio for micro:bit (python)


here is my code for my microbit in python

so i want to know how do i send the target_x and the target_y from the microbit 1 to the second microbit ?

microbit 1 :

radio.on()
target_x = random.randint(0,4)
target_y = random.randint(0,4)
if button_a.was.pressed():
    radio.send()

microbit 2 :

radio.on()
order = radio.receive()
microbit.display.set_pixel(target_x,target_y,7)

so i want to know how do i send the target_x and the target_y from the microbit 1 to the second microbit ?

thanks for your answers


Solution

  • I tested the code below using two microbits. I put in an 'except, try' clause on the receiver in case the message is corrupted. There is more error checking that should be implemented to make a reliable wireless interface, but this answers the question.

    radio_send_randints.py

    ''' transmit random x and y on button push '''
    import random
    from microbit import *
    import radio
    
    radio.config(group=0)
    radio.on()
    
    while True:
        if button_a.was_pressed():
            target_x = random.randint(0,4)
            target_y = random.randint(4)
            message = "{},{}".format(target_x, target_y)
            radio.send(message)
        sleep(100)
    

    radio_receive_randints.py

    from microbit import *
    import radio
    
    radio.config(group=0)
    radio.on()
    
    while True:
        incoming = radio.receive()
        if incoming:
            try:
                target_x, target_y = incoming.split(',')
            except:
                continue
            display.set_pixel(int(target_x), int(target_y), 7)