CircuitPython UART Serial

This quick-start example shows how you can create a UART device for communicating with hardware serial devices

Copy and paste the code block into using your favorite text editor, and save the file, to run the demo

# Trinket IO demo - USB/Serial echo

from digitalio import DigitalInOut, Direction
import board
import busio
import time

led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT

# You can also use board.TX and board.RX for prettier code!
uart = busio.UART(board.D4, board.D3, baudrate=9600)

while True:
    data =  # read up to 32 bytes
    #print(data)          # this is a bytearray type

    if data != None:
        led.value = True

	datastr = ''.join([chr(b) for b in data]) # convert bytearray to string
	print(datastr, end="")

        led.value = False

In addition to the USB-serial connection you use for the REPL, there is also a hardware UART you can use. This is handy to talk to UART devices like GPS's, some sensors, or other microcontrollers!

You can create a new UART object with uart = busio.UART(board.D4, board.D3, baudrate=9600) You can use either D4 and D3 or D0 and D2 as the transmitting and receiving pins (respectively) on the Trinket M0 - you can even have two UART objects!

We've marked D4 and D3 as RX and RX on the bottom of the PCB so our example will use those. Set the baudrate to whatever you like.

Once the object is created you read data in with read(numbytes) where you can specify the max number of bytes. It will return a bytearray type object if anything was received already. Note it will always return immediately because there is an internal buffer! So read as much data as you can 'digest'.

If there is no data available, read() will return None, so check for that before continuing.

The data that is returned is in a byte array, if you want to convert it to a string, you can use this handy line of code which will run chr() on each byte:

datastr = ''.join([chr(b) for b in data]) # convert bytearray to string

To run this demo, you'll need something to generate UART data. We connected up a GPS!

Last updated on 2018-03-19 at 11.19.46 PM Published on 2017-08-23 at 05.57.02 PM