Sending data over Serial#
When a Pico is connected to a computer using a USB cable it is possible to send data over the serial connection
Requirements
A Pico
A Computer connected to the Pico by USB
Set-up#
Connect the Pico and Computer together using a USB cable.
The following program is run on the Computer, Not The Pico
"""Simple program to log data sent over the serial port"""
import sys
import datetime as dt
import serial
def readserial(comport: str, baudrate: int):
"""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
"""
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:
#This assumes the data is JSON formated
data = json.loads(data)
print(data)
# This can be saved to file or database depending on need
elif data:
#This just prints it, but it could be an error from the pico and therefore treated accordingly
print(data)
except KeyboardInterrupt:
print("Ending Logging")
sys.exit()
port = # The COM port that is connect
bau = 115200 # The baud rate of the connection, normally 115200
readserial(port, baud)
The code on the Pico is then
import os
import microcontroller
import time
import json
import board
import adafruit_dht
dht = adafruit_dht.DHT11(board.GP0)
#Retrieve variables from settings.toml
inatorname = os.getenv("INATORNAME")
accTime = os.getenv('ACQUIRETIME') #how often to acquire and transmit data
recTime = os.getenv('RECONTIME') #how oftern to reconnect in seconds
while True:
temp = dht.temperature
humidity = dht.humidity
#Create dictionary
json_dict = {"inator":inatorname,"temperature":temp,"humidity":humidity} # Send data with JSON syntax
json_data = json.dumps(json_dict)
print(f"{json_data}")
time.sleep(accTime)