For my research on increasing benefits to crops from symbiotic nitrogen fixation, I’m using a PyBoard to output voltages to control pumps and mass-flow controllers and to read voltages and serial data from sensors. It’s more capable than the Arduino (which is also great) and runs Python! I can talk to it with the “screen” command in the Linux terminal running on a Raspberry Pi, but for more-sophisticated control and data processing, I wanted to read and write to the PyBoard from a Python program on the Raspberry Pi. I thought others might also find this useful, so here are simple example Python programs for the Raspberry Pi and PyBoard.
Python code for Raspberry Pi
print(“This runs on Raspberry Pi controlling PyBoard via USB.”)
print(“Reads and prints output from PyBoard until line with ?”)
print(“Then sends one-line command to PyBoard.”)
from time import sleep
import sys, datetime, serial
# Set up to communicate with PyBoard.
# port could be ACM1, USB0, etc.
# Start PyBoard.
ser.write(“\x03”.encode()) # CTRL-C
ser.write(“\x04”.encode()) # CTRL-D
while True : # Read from PyBoard until ? prompt.
line=ser.readline().decode().strip() # Read line from PyBoard.
if “?” in line : # Prompt from PyBoard?
command=input(“:”) # Yes; send command to PyBoard.
Python code for PyBoard
# This runs on Pyboard to communicate with Raspberry Pi via USB
def USB2line() : # Read a line from USB port.
while True: # Loop over bytes from USB.
while not usb.any(): # Wait for byte on USB
dummy=0 # Just waiting.
byte=usb.read(1) # Read one byte.
char=byte.decode() # Convert to character.
line=line+char # Add to line.
if len(line)>2 and char==”\n” : # End of line?
def line2USB(line) : # Output a line to USB port.
# Simple code to test above functions.
line2USB(“\nThis test program just echos commands.”)
while True : # Echo commands.
command=USB2line().strip() # Read line from Pi.