Raspberry PI controlling an Arduino via the pyfirmata protocol
The Raspberry PI is good for a lot of things from computer clusters to home automation but its missing a few things such as a real time clock, terminal/barrel power connector, or Analog pins. The Arduino has analog pins that can be read by the USB virtual serial port from the Raspberry PI.
In MagPI issue 7, has a great article on using the firmata protocol to communicate between Arduino and the Raspberry PI.
Requirements
- A raspberry PI
- A Arduino
- USB Cable A to B
- pyFirmata python library (documentation)
Install and setup
- Enable SSH on the Raspberry PI
- Install Adafruit Learning System Raspberry Pi WebIDE
- Get the required packages:
sudo apt-get install python-serial mercurial
- Install pyFirmata
sudo apt-get install python-serial mercurial hg clone https://bitbucket.org/tino/pyfirmata cd pyfirmata sudo python setup.py install cd .. ; sudo rm -r pyfirmata
Source code
import pyfirmata
# Create a new board, specifying serial port
board = pyfirmata.Arduino('/dev/ttyACM0')
# start an iterator thread so that serial buffer doesn't overflow
it = pyfirmata.util.Iterator(board)
it.start()
# set up pins
pin0=board.get_pin('a:0:i') # A0 Input (LM35)
pin3=board.get_pin('d:3:p') # D3 PWM Output (LED)
# IMPORTANT! discard first reads until A0 gets something valid
while pin0.read() is None:
pass
while True :
print "PWM: " + str( pin0.read() )
board.pass_time(1) # pause 1 second
board.exit()
Leave a comment