Serial#
It is very common to connect to a microprocessor using a serial port. This is often the method used to upload programmes.
This makes it easy to use as a simple logging channel. Below is a simple Python example code that will connect to a COM port that has a microprocessor connected
Note that this is a blocking implementation, while reading from the serial port the code will remain in an infinite loop An try catch loop is used to catch the ctrl+c used to end this programme. Replace <COMPORT> with the name of the COM port you wish to connect to
import sys
import datetime as dt
import json
import argparse as arg
import serial
def readserial(comport: str, baudrate: int, timestamp=False):
"""Function to read value from a serial port
Assumes it is a json formatted string
Parameters
----------
comport : str
the com port to connect to
baudrate : int
the baud rate of the connection
timestamp : bool, optional
Whether to add timestamp to data, by default False
"""
ser = serial.Serial(
comport, baudrate, timeout=0.1
) # 1/timeout is the frequency at which the port is read
try:
while True:
data = ser.readline().decode().strip()
if "{" in data:
data = json.loads(data)
if timestamp:
ct = dt.datetime.now()
data = {"timestamp": int(ct.timestamp()), **data}
print(data)
# This can be saved to file or database depending on need
elif data:
print(data)
except KeyboardInterrupt:
print("Ending Logging")
sys.exit()
if __name__ == "__main__":
out = get_formatted_datetime()
print(f"Readying Logging at:{out}")
port = <COMPORT>
baud = 115200 #default for Pico
timestamp = True
print(f"Connecting to {port}, with Baud rate {baud}")
if timestamp:
print("Time stamps will be added")
readserial(port, baud, timestamp)