2

I'm working on a project involving a Node website and an Adafruit 8x8 button matrix using the Feather M4 Express microcontroller and CircuitPython. I am trying to sort out clean serial communication between the website and the button grid via USB.

This is the current loop I have on the microcontroller, which is supposed to just check for serial input, and print it if it exists.

while True:
    # the trellis can only be read every 17 millisecons or so
    trellis.sync()

    if supervisor.runtime.serial_bytes_available:
        data = input()
        print(data)

    time.sleep(0.02)

This works for the first iteration. The problem is, after the first input() call, supervisor.runtime.serial_bytes_available isn't being reset to False. Hence, in the second iteration, the microcontroller hangs at input() until I send it something over serial. This happens for every following iteration.

How can I make sure supervisor.runtime.serial_bytes_available will be set back to False after I read the input?

1 Answers1

1

supervisor.runtime.serial_bytes_available is giving you the number of bytes to read as an int but can still be used as a boolean value with zero equating to False. It will be dependent on what data you are sending as to whether input() reads all of that data, i.e. data like "a line\na partial line" will hang on the second line. You can read any data with sys.stdin.read() but you have to do a little extra work to coalesce/parse that data. Some caution on end of line characters is also required, you may find sequences like CRLF in data.

Depending on what you are sending you may hit some issues with control characters. This can be disabled for the problematic Control-C (0x03 causing KeyboardInterrupt) with use micropython.kbd_intr() of according to Adafruit Forums: replace ctrl-c, e.g. by ctrl-g

There's some overlap here with the question/answer in How to do non blocking usb serial input in circuit python?

KevinJWalters
  • 193
  • 1
  • 7