pythonvariablesserial-portbbc-microbit

Is it possible to communicate values to a microbit through a serial port using python?


Unlike the other questions that you may recommend, I am not trying to get the microbit to send me information, I am trying to send information to the microbit.

My goal here is to send through three integers in a list to a microbit, specifically through the serial port as I am trying to send these variables as quickly as possible.

I have absolutely no idea what I am doing here, as all the microbit guides I could find only went through taking information from a microbit.

I have tried going into TeraTerm and adjusting variables from there, but the microbit seems to be unable to understand when the variables have been changed through the TeraTerm program. For example:

In microbit:

serial.redirect_to_usb()
colour == 0
if colour == 1:
display.show(display.HAPPY)

In Tera Term, I enter:

colour = 1

Nothing happens. However, when I type:

colour == 1

It responds with "True".

Is there any way to send my variables to my microbit through python? I don't just mean through TeraTerm, but through python actively automating the task.

I am currently using python 3x, and the latest version of TeraTerm.


Solution

  • This micropython code enables a micro:bit v1 to respond to key presses (a, b, c) made on a serial terminal on a PC which is connected to the micro:bit. I use the tio serial terminal. I programmed the micro:bit using the online editor here: https://python.microbit.org/v/3

    from microbit import *
    
    
    # Code in a 'while True:' loop repeats forever
    display.show(Image.CONFUSED)
    while True:
        data = uart.readline()
        if data == b'a':
            display.show(Image.ARROW_E)
        if data == b'b':
            display.show(Image.ARROW_N)
        if data == b'c':
            display.show(Image.ARROW_W)
        sleep(500)
    

    The data from the serial port is received as bytes, so you need to specify using the syntax:

    b'a'
    

    to identify the 'a' character sent from the serial terminal.