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.

Evan Almloff
  • 83
  • 1
  • 6

2 Answers2

1

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

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.

KevinJWalters
  • 193
  • 1
  • 7
  • BTW, sending binary data to CircuitPython over serial console might be problematic, [GH: adafruit/circuitpython 'getch()' #231](https://github.com/adafruit/circuitpython/issues/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](https://forums.adafruit.com/viewtopic.php?f=60&t=173071&p=847223&hilit=disable+KeyboardInterrupt+ctrl-c). – KevinJWalters Jan 26 '21 at 14:17