With most devboards using the USB connection for the REPL or direct control, you may want to have a secondary USB (or serial) connection - to the same computer or maybe another one. You can also of course use a UART wireless link, XBee, etc. UART is pretty common!

The following code demonstrates logging messages to a board serial (UART) port (usually pin TX):

# SPDX-FileCopyrightText: 2018 Dave Astels for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
UART based message handler for CircuitPython logging.

Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!

Written by Dave Astels for Adafruit Industries
Copyright (c) 2018 Adafruit Industries
Licensed under the MIT license.

All text above must be included in any redistribution.
"""


# Example:
#
# import board
# import busio
# from uart_handler import UartHandler
# import adafruit_logging as logging
#
# uart = busio.UART(board.TX, board.RX, baudrate=115200)
# logger = logging.getLogger('uart')
# logger.addHandler(UartHandler(uart))
# logger.level = logging.INFO
# logger.info('testing')

from adafruit_logging import Handler

class UartHandler(Handler):
    """Send logging output to a serial port."""

    def __init__(self, uart):
        """Create an instance.

        :param uart: the busio.UART instance to which to write messages
        """
        self._uart = uart

    def format(self, record):
        """Generate a string to log.

        :param record: The record (message object) to be logged
        """
        return super().format(record) + '\r\n'

    def emit(self, record):
        """Generate the message and write it to the UART.

        :param record: The record (message object) to be logged
        """
        self._uart.write(bytes(self.format(record), 'utf-8'))

This does a few things. 

First, it uses the UART instance passed in, giving you the flexibility to use the serial port you want.

It provides its own format method which calls the superclass's format to build the output string (that's the LoggingHandler class) and appends a newline sequence (a carriage return then a line feed) since write doesn't automatically terminate the line the way print does.

The emit method uses format to build the string, converts it to a bytearray and writes the bytes to the UART.

You would use it like in the following example:

import board
import busio
from uart_handler import UartHandler
import adafruit_logging as logging

uart = busio.UART(board.TX, board.RX, baudrate=115200)
logger = logging.getLogger('test')
logger.addHandler(UartHandler(uart))
logger.setLevel(logging.INFO)
logger.info('testing')

This guide was first published on Mar 18, 2019. It was last updated on Mar 28, 2024.

This page (Log to UART) was last updated on Mar 28, 2024.

Text editor powered by tinymce.