Controlling a PyBoard with a Raspberry Pi

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.
print (line)
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
import pyb
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. # 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?
return 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.
line=command+” OK”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s