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.

The QT Py M0 does not have a little red LED. Therefore, you must connect an external LED and edit this example for it to work. Follow the wiring diagram and steps below to run this example on QT Py M0.
  • LED + to QT Py SCK
  • LED - to 470Ω resistor
  • 470Ω resistor to QT Py GND

In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory CircuitPython_Essentials/CircuitPython_UART/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""CircuitPython Essentials UART Serial example"""
import board
import busio
import digitalio

# For most CircuitPython boards:
led = digitalio.DigitalInOut(board.LED)
# For QT Py M0:
# led = digitalio.DigitalInOut(board.SCK)
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
Note: To "comment out" a line, put a # and a space before it. To "uncomment" a line, remove the # + space from the beginning of the line.

For QT Py M0, you'll need to comment out led = DigitalInOut(board.LED) and uncomment led = DigitalInOut(board.SCK). The UART code remains the same.

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 and Circuit Playground Bluefruit

  • 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.

QT Py M0

  • Connect 3V on the QT Py to VIN on the GPS.
  • Connect GND on the QT Py to GND on the GPS.
  • Connect RX on the QT Py to TX on the GPS.
  • Connect TX on the QT Py 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.

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

In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory CircuitPython_Essentials/UART_Test_Script/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""CircuitPython Essentials UART possible pin-pair identifying script"""
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
        if is_hardware_uart(tx_pin, rx_pin):
            print("RX pin:", rx_pin, "\t TX pin:", tx_pin)

Trinket M0: Create UART before I2C

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

>>> import board
>>> uart = board.UART()   # Uses pins 4 and 3 for TX and RX, baudrate 9600.
>>> i2c = board.I2C()     # Uses pins 2 and 0 for SCL and SDA.

# or alternatively,

Creating the I2C object first does not work:

>>> import board
>>> i2c = board.I2C()     # Uses pins 2 and 0 for SCL and SDA.
>>> uart = board.UART()   # Uses pins 4 and 3 for TX and RX, baudrate 9600.
Traceback (most recent call last):
File "", line 1, in 
ValueError: Invalid pins

This guide was first published on May 27, 2018. It was last updated on Mar 18, 2024.

This page (CircuitPython UART Serial) was last updated on Mar 18, 2024.

Text editor powered by tinymce.