adafruitmicropython

Receive data from host computer using Circuit Python on Circuit Playground Express


I am using a Circuit Playground Express from Adafruit, and I'm programming it with Circuit Python.

I want to read data transmitted from the computer to which the Circuit Playground Express is connected via USB. Using input() works fine, but I would rather get the buffer of the serial instead, so that the loop would go on while there's no input. Something like serial.read().

import serial does not work on Circuit Python, or maybe I must install something. Is there anything else I could do to read the serial buffer using Circuit Python?


Solution

  • This is now somewhat possible! In the January stable release of CircuitPython 3.1.2 the function serial_bytes_available was added to the supervisor module.

    This allows you to poll the availability of serial bytes.

    For example in the CircuitPython firmware (i.e. boot.py) a serial echo example would be:

    import supervisor
    
    def serial_read():
       if supervisor.runtime.serial_bytes_available():
           value = input()
           print(value)
    

    and ensure when you create the serial device object on the host side you set the timeout wait to be very small (i.e. 0.01).

    i.e in python:

    import serial
    
    ser = serial.Serial(
                 '/dev/ttyACM0',
                 baudrate=115200,
                 timeout=0.01)
    
    ser.write(b'HELLO from CircuitPython\n')
    x = ser.readlines()
    print("received: {}".format(x))