如何在电路 python 中实现非阻塞 USB 串行输入?

How to do non blocking usb serial input in circuit python?

我正在尝试使用串行读写在我的计算机上将 micropython 板与 python 连接起来,但是我找不到在 micro[= 中读取 usb 串行数据的方法19=] 是非阻塞的。

基本上我想调用输入函数而不需要输入继续。 (类似于 https://github.com/adafruit/circuitpython/pull/1186 但对于 USB)

我试过使用 tasko、uselect(导入库失败,我找不到下载)和 await 函数。我不确定是否有办法做到这一点,但我们将不胜感激。

对于 CircuitPython,有 supervisor.runtime.serial_bytes_available 可以为您想做的事情提供构建块。

这在 Adafruit Forums: Receive commands from the computer via USB 上讨论。

基于相对新增的 usb_cdc buildin (>= 7.0.0) 你可以这样做:

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()

这是一个非常简单的例子。 如果你想支持 universal line ends 并且一次发送多个命令,行尾处理可能会变得非常复杂...

我基于此创建了一个库:CircuitPython_nonblocking_serialinput