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 main.py using your favorite text editor, and save the file, to run the demo

# Gemma IO demo - USB/Serial echo

from digitalio import *
from board import *
import busio
import time

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

uart = busio.UART(D0, D2, baudrate=9600)

while True:
    data = uart.read(32)  # 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(D0, D2, baudrate=9600) You can use only D0 and D2 as the transmitting and receiving pins on the Gemma M0. 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 2017-12-01 at 04.59.09 PM Published on 2017-07-26 at 06.08.30 PM