Capturing Serial Output with Python

Sept. 8, 2020

Using PySerial to capture serial console outputs


Many of the IoT devices do not have WiFi or 3G/4G connections. They are simple single-board devices that lack computing resources in favor of low power consumption, cost, and footprint. In which case, we can treat it as an extension to a computing platform (such as Raspberry Pi) as a sensor and capture the output via serial.

For example, I have been playing around with the Adafruit CLUE board that really packs a punch when it comes to the number of sensors it houses on a small form factor:

CLUE-Front

CLUE-Back

Image Source: https://learn.adafruit.com/adafruit-clue/overview

While it does have a Bluetooth chip on board, it was simply easier to capture the serial output from the board. For example, I can use this modified version of the script, https://learn.adafruit.com/adafruit-clue/clue-temperature-and-humidity-monitor, to measure and display temperature:

CLUE-Temp-Script

The print statement in the script will print the output to the onboard display as well as to the serial port. I can find the serial port on my computer:

$ ls /dev/cu.usb*

/dev/cu.usbmodem141401

Then use the following script to grab the serial output:

import serial

serial = serial.Serial('/dev/cu.usbmodem141401')

while True:

....output = serial.readline().strip()

....output_string = output.decode("utf-8")

....print('This is the serial output: ' + str(output_string))

Here is the output upon execution:

$ python serial_test.py

This is the serial output: 29.0111

This is the serial output: 29.0086

This is the serial output: 29.0061

This is the serial output: 29.0186

This is the serial output: 29.0137

This is the serial output: 29.0111

This is the serial output: 29.0186

This is the serial output: 29.0137

This makes it really easy to integrate the CLUE board with other small form factor computing devices that are more powerful, such as the Rasperry Pi.

I plan to spend a lot more time with IoT sensors and computers so let me know in the comments if you have some project ideas.

Happy coding!

Eric

Return to blog