1

I am trying to interface a micropython board with python on my computer using serial read and write, however I can't find a way to read usb serial data in micropython that is non-blocking.

Basicly I want to call the input function without requiring an input to move on. (something like https://github.com/adafruit/circuitpython/pull/1186 but for usb)

I have tried using tasko, uselect (it failed to import the library and I can't find a download), and await functions. I'm not sure it there is a way to do this, but any help would be appreciated.

2 Answers 2

2

based on the relative new added usb_cdc buildin (>= 7.0.0) you can do something like this:

def read_serial(serial):
    available = serial.in_waiting
    while available:
        raw = serial.read(available)
        text = raw.decode("utf-8")
        available = serial.in_waiting
    return text

# main
buffer = ""
serial = usb_cdc.console
while True:
    buffer += read_serial(serial)
    if buffer.endswith("\n"):
        # strip line end
        input_line = buffer[:-1]
        # clear buffer
        buffer = ""
        # handle input
        handle_your_input(input_line)

    do_your_other_stuff()

this is a very simple example. the line-end handling could get very complex if you want to support universal line ends and multiple commands send at once...

i have created a library based on this: CircuitPython_nonblocking_serialinput

Sign up to request clarification or add additional context in comments.

Comments

0

For CircuitPython there's supervisor.runtime.serial_bytes_available which may provide the building block for what you want to do.

This is discussed on Adafruit Forums: Receive commands from the computer via USB.

1 Comment

BTW, sending binary data to CircuitPython over serial console might be problematic, GH: adafruit/circuitpython 'getch()' #231 mentions this at the end with control-c and control-d (that one seems odd) being picked up by REPL and a prospective feature to improve this. There might be a workaround, there's mention of using the not-supported-in-CircuitPython micropython.kbd_Intr() in Adafruit Forums: replace ctrl-c, e.g. by ctrl-g.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.