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

# RunPyBoard.py
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.
ser=serial.Serial(
port=”/dev/ttyACM0″,
baudrate=9600,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=None)
# 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.
line2PyBoard=command+”\n”
ser.write(line2PyBoard.encode())

Python code for PyBoard

# main.py
# This runs on Pyboard to communicate with Raspberry Pi via USB
import pyb
usb=pyb.USB_VCP()
def USB2line() : # Read a line from USB port.
line=””
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?
return line
def line2USB(line) : # Output a line to USB port.
usb.write((line+”\n”).encode())
return
# Simple code to test above functions.
line2USB(“\nThis test program just echos commands.”)
while True : # Echo commands.
line2USB(“Command?”)
command=USB2line().strip() # Read line from Pi.
line=command+” OK”
line2USB(line)

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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