Control your Arduino via Python with your Raspberry Pi
I recently ran across the nanpy library for Python when looking at different internet radio projects using the Raspberry Pi. It allows you to easily control your Arduino from Python, and it installs on the Pi in a snap:
First, install Arduino:
$ sudo apt-get install arduino
Next, install the nanpy source: This is needed to later build the new Arduino firmware:
$ cd ~ $ curl -O https://pypi.python.org/packages/source/n/nanpy/nanpy-v0.8.tar.gz $ tar xvf nanpy-v0.8.tar.gz $ rm nanpy-v0.8.tar.gz
Now install the required Python libs:
$ sudo pip install nanpy $ sudo pip install pyserial
Hook up your Arduino to one of the Pi’s USB ports, and create/upload the new firmware (using an Arduino Uno as an example):
$ cd ~/nanpy/firmware $ export BOARD=uno $ make $ make upload
From there, programming my Pi via the Adafruit WebIDE (and with my Arduino hooked up to a breadboard with the required led’s and resistors), I recreated a few basic Arduino sketches to see how it worked. It worked as expected, simple and easy.
Here is a port of the basic Arduino Blink sketch:
from nanpy import Arduino as A led = 13 # SETUP: A.pinMode(led, A.OUTPUT) # LOOP: while True: A.digitalWrite(led, A.HIGH); # turn the LED on (HIGH is the voltage level) print "blink on" A.delay(1000); # wait for a second A.digitalWrite(led, A.LOW); # turn the LED off by making the voltage LOW print "blink off" A.delay(1000);
And a port of the basic Fade sketch:
from nanpy import Arduino as A led = 9 brightness = 0 fadeAmount = 5 # SETUP: A.pinMode(led, A.OUTPUT) # LOOP: while True: # set the brightness of pin 9: A.analogWrite(led, brightness) # change the brightness for next time through the loop: brightness += fadeAmount # reverse the direction of the fading at the ends of the fade: if brightness == 0 or brightness == 255: fadeAmount = -fadeAmount # wait for 30 milliseconds to see the dimming effect A.delay(30)
Only a few core libraries are currently supported. To see the list, you can visit this page.
On a side note I should point out I went to great lengths to get this working on my Mac, without a lot of success. You can check out my Python Wiki post on it, under the “Mac Notes” section.