CircuitPython UART Serial

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 GPSs, some sensors, or other microcontrollers!

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

To use this example, you'll need something to generate the UART data. We've used a GPS! Note that the GPS will give you UART data without getting a fix on your location. You can use this example right from your desk! You'll have data to read, it simply won't include your actual location.

You'll need the adafruit_bus_device library folder if you don't already have it in your /lib folder! You can get it from the CircuitPython Library Bundle. If you need help installing the library, check out the CircuitPython Libraries page.

Copy and paste the code into code.py using your favorite editor, and save the file.

# CircuitPython Demo - USB/Serial echo

import board
import busio
import digitalio

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

uart = busio.UART(board.TX, board.RX, baudrate=9600)

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

    if data is not None:
        led.value = True

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

        led.value = False

The Code

First we create the UART object. We provide the pins we'd like to use, board.TX and board.RX, and we set the baudrate=9600. While these pins are labeled on most of the boards, be aware that RX and TX are not labeled on Gemma, and are labeled on the bottom of Trinket. See the diagrams below for help with finding the correct pins on your board.

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 byte array 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

Your results will look something like this:

For more information about the data you're reading and the Ultimate GPS, check out the Ultimate GPS guide: https://learn.adafruit.com/adafruit-ultimate-gps

Wire It Up

You'll need a couple of things to connect the GPS to your board.

For Gemma M0 and Circuit Playground Express, you can use use alligator clips to connect to the Flora Ultimate GPS Module.

For Trinket M0, Feather M0 Express, Metro M0 Express and ItsyBitsy M0 Express, you'll need a breadboard and jumper wires to connect to the Ultimate GPS Breakout.

We've included diagrams show you how to connect the GPS to your board. In these diagrams, the wire colors match the same pins on each board.

  • The black wire connects between the ground pins.
  • The red wire connects between the power pins on the GPS and your board.
  • The blue wire connects from TX on the GPS to RX on your board.
  • The white wire connects from RX on the GPS to TX on your board.

Check out the list below for a diagram of your specific board!

Watch out! A common mixup with UART serial is that RX on one board connects to TX on the other! However, sometimes boards have RX labeled TX and vice versa. So, you'll want to start with RX connected to TX, but if that doesn't work, try the other way around!

Circuit Playground Express

  • Connect 3.3v on your CPX to 3.3v on your GPS.
  • Connect GND on your CPX to GND on your GPS.
  • Connect RX/A6 on your CPX to TX on your GPS.
  • Connect TX/A7 on your CPX to RX on your GPS.

Trinket M0

  • Connect USB on the Trinket to VIN on the GPS.
  • Connect Gnd on the Trinket to GND on the GPS.
  • Connect D3 on the Trinket to TX on the GPS.
  • Connect D4 on the Trinket to RX on the GPS.

Gemma M0

  • Connect 3vo on the Gemma to 3.3v on the GPS.
  • Connect GND on the Gemma to GND on the GPS.
  • Connect A1/D2 on the Gemma to TX on the GPS.
  • Connect A2/D0 on the Gemma to RX on the GPS.

Feather M0 Express and Feather M4 Express

  • Connect USB on the Feather to VIN on the GPS.
  • Connect GND on the Feather to GND on the GPS.
  • Connect RX on the Feather to TX on the GPS.
  • Connect TX on the Feather to RX on the GPS.

ItsyBitsy M0 Express and ItsyBitsy M4 Express

  • Connect USB on the ItsyBitsy to VIN on the GPS
  • Connect G on the ItsyBitsy to GND on the GPS.
  • Connect RX/0 on the ItsyBitsy to TX on the GPS.
  • Connect TX/1 on the ItsyBitsy to RX on the GPS.

Metro M0 Express and Metro M4 Express

  • Connect 5V on the Metro to VIN on the GPS.
  • Connect GND on the Metro to GND on the GPS.
  • Connect RX/D0 on the Metro to TX on the GPS.
  • Connect TX/D1 on the Metro to RX on the GPS.

Where's my UART?

On the SAMD21, we have the flexibility of using a wide range of pins for UART. Compare this to some chips like the ESP8266 with fixed UART pins. The good news is you can use many but not all pins. Given the large number of SAMD boards we have, its impossible to guarantee anything other than the labeled 'TX' and 'RX'. So, if you want some other setup, or multiple UARTs, how will you find those pins? Easy! We've written a handy script.

All you need to do is copy this file to your board, rename it code.py, connect to the serial console and check out the output! The results print out a nice handy list of RX and TX pin pairs that you can use.

These are the results from a Trinket M0, your output may vary and it might be very long. For more details about UARTs and SERCOMs check out our detailed guide here

import board
import busio
from microcontroller import Pin


def is_hardware_uart(tx, rx):
    try:
        p = busio.UART(tx, rx)
        p.deinit()
        return True
    except ValueError:
        return False


def get_unique_pins():
    exclude = ['NEOPIXEL', 'APA102_MOSI', 'APA102_SCK']
    pins = [pin for pin in [
        getattr(board, p) for p in dir(board) if p not in exclude]
            if isinstance(pin, Pin)]
    unique = []
    for p in pins:
        if p not in unique:
            unique.append(p)
    return unique


for tx_pin in get_unique_pins():
    for rx_pin in get_unique_pins():
        if rx_pin is tx_pin:
            continue
        else:
            if is_hardware_uart(tx_pin, rx_pin):
                print("RX pin:", rx_pin, "\t TX pin:", tx_pin)
            else:
                pass

Trinket M0: Create UART before I2C

On the Trinket M0 (only), if you are using both busio.UART and busio.I2C, you must create the UART object first, e.g.:

>>> import board,busio
>>> uart = busio.UART(board.TX, board.RX)
>>> i2c = busio.I2C(board.SCL, board.SDA)

Creating busio.I2C first does not work:

>>> import board,busio
>>> i2c = busio.I2C(board.SCL, board.SDA)
>>> uart = busio.UART(board.TX, board.RX)
Traceback (most recent call last):
File "", line 1, in
ValueError: Invalid pins

This guide was first published on May 03, 2017. It was last updated on Sep 21, 2018. This page (CircuitPython UART Serial) was last updated on Jul 13, 2018.