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 json
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
baud = 115200 # The baud rate of the connection, normally 115200
readserial(port, baud)
The code on the Pico is then below. Note that this code can recieve commands on the serial port
import os
import sys
import microcontroller
import time
import json
import board
import supervisor
def hola(input_buffer:str):
print(f"Hello from {inatorname}")
def reading():
try:
temp = 50 #Fixed as an example
humidity = 45 # fixed as an example
#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}")
return json_data
except RuntimeError as e:
print(f"Sensor read error: {e}")
return None
#Retrieve variables from settings.toml
inatorname = os.getenv("INATORNAME")
accTime = float(os.getenv('ACQUIRETIME')) #how often to acquire and transmit data
last_publish = 0
input_buffer = ""
while True:
now = time.monotonic()
if supervisor.runtime.serial_bytes_available:
char = sys.stdin.read(1)
if char in ("\n", "\r"):
if input_buffer:
print(f"Received command: {input_buffer}")
if input_buffer == "hola":
hola(input_buffer)
if input_buffer == "read":
json_data = reading()
if json_data:
print(f"{json_data}")
input_buffer = ""
else:
input_buffer += char
if now - last_publish >= accTime:
json_data = reading()
if json_data:
print(f"{json_data}")
last_publish = now
time.sleep(0.01)
in the settings.toml file on the Pico put the following:
INATORNAME = "NAME"
ACQUIRETIME = 5