# Raspberry Pi Sensor and Actuator Control

Author: Jack Minardi

I gave a talk at SciPy 2013 titled `open('dev/real_world')` Raspberry Pi Sensor and Actuator Control. You can find the video on youtube, the slides on google drive and I will summarize the content here.

Typically as a programmer you will work with data on disk, and if you are lucky you will draw pictures on the screen. This is in contrast to physical computing which allows you as a programmer to work with data sensed from the real world and with data sent to control devices that move in the real world.

physical computing at work. (source)

# Goal

Use a Raspberry Pi to read in accelerometer value and to control a servo motor.

# Definitions

• Raspberry Pi
• Small \$35 Linux computer with 2 USB ports, HDMI out, Ethernet, and most importantly…
• GPIO Pins
• General Purpose Input/Output Pins
• This is the component that truly enables “physical computing”. You as a programmer can set the voltage high or low on each pin, which is how you will talk to actuators. You can also read what the voltage is currently on each pin. This is how sensors will talk back to you. It is important to note that each pin represents a binary state, you can only output a 0 or a 1, nothing in between.

In this article I will go over four basic Python projects to demonstrate the hardware capabilities of the Raspberry Pi. Those projects are:

• Stream data.
• Control a servo.

An LED is a Light Emitting Diode. A diode is a circuit element that allows current to flow in one direction but not the other. Light emitting means … it emits light. Your typical LED needs current in the range of 10-30 mA and will drop about 2-3 volts. If you connect an LED directly to your Pi’s GPIO it will source much more than 30 mA and will probably fry your LED. To prevent this we have to put a resistor. If you want to do math you can calculate the appropriate resistance using the following equation:

`R = (Vs - Vd) / I`

But if you don’t want to do math then pick a resistor between 500-1500 ohms. Once you’ve gathered up all your circuit elements (LED and resistor), build this circuit on a breadboard:

thats not so bad, is it?

The code is also pretty simple. But first you will need to install RPi.GPIO. (It might come preinstalled on your OS.)

```import time
from itertools import cycle
import RPi.GPIO as io

io.setmode(io.BCM)
io.setup(12, io.OUT)

o = cycle([1, 0])
while True:
io.output(12, o.next())
time.sleep(0.5)```

The important lines basically are:

```io.setup(12, io.OUT)
io.output(12, 1)```

These lines of code setup pin 12 as an output, and then output a 1 (3.3 volts). Run the above code connected to the circuit and you should see your LED blinking on and off every half second.

A pot is short for potentiometer, which is a variable resistor. This is just a fancy word for knob. Basically by turning the knob you affect the resistance, which affects the voltage across the pot. (`V = IR`, remember?). Changing voltage relative to some physical value is how many sensors work, and this class of sensor is known as an analog sensor. Remember when I said the GPIO pins can only represent a binary state? We will have to call in the aide of some more silicon to convert that analog voltage value into a binary stream of bits our Pi can handle.

That chunk of silicon is refered to as an Analog-to-Digital Converter (ADC). The one I like is called MCP3008, it has 8 10-bit channels, meaning we can read 8 sensors values with a resolution of 1024 each (2^10). This will map our input voltage of 0 – 3.3 volts to an integer between 0 and 1023.

I’ve turned the Pi into ephemeral yellow labels to simplify the diagram

To talk to the chip we will need a python package called spidev. For more information about the package and how it works with the MCP3008 check out this great blog post

With spidev installed and the circuit built, run the following program to read live sensor values and print them to stdout.

```import spidev
import time

spi = spidev.SpiDev()
spi.open(0,0)

if not 0 <= adcnum <= 7:
return -1
adcout = ((r[1] & 3) << 8) + r[2]

while True:
print val
time.sleep(0.5)```

The most important parts are these two lines:

```r = spi.xfer2([1, (8+adcnum)<<4, 0])
adcout = ((r[1] & 3) << 8) + r[2]```

They send the read command and extract the relevant returned bits. See the blog post I linked above for more information on what is going on here.

# Stream data.

To stream data over the wire we will be using the ØMQ networking library and implementing the REQUEST/REPLY pattern. ØMQ makes it super simple to set up a client and server in Python. The following is a complete working example.

## Server

```import zmq

context = zmq.Context()
socket = context.socket(
zmq.REP)
socket.bind('tcp://*:1980')

while True:
message = socket.recv()
print message
socket.send("I'm here")```

## Client

```import zmq

context = zmq.Context()
socket = context.socket(
zmq.REQ)
a = 'tcp://192.168.1.6:1980'
socket.connect(a)

for request in range(10):
socket.send('You home?')
message = socket.recv()
print message```

Now we can use traits and enaml to make a pretty UI on the client side. Check out the acc_plot demo in the github repo to see an example of the Pi streaming data over the wire to be plotted by a client.

# Control a servo

Servos are (often small) motors which you can drive to certain positions. For example, for a given servo you may be able to set the drive shaft from 0 to 18o degrees, or anywhere in between. As you can imagine, this could be useful for a lot of tasks, not least of which is robotics.

Shaft rotation is controlled by Pulse Width Modulation (PWM) in which you encode information in the duration of a high voltage pulse on the GPIO pins. Most hobby servos follow a standard pulse width meaning. A 0.5 ms pulse means go to your min position and a 2.5 ms pulse means go to your max position. Now repeat this pulse every 20 ms and you’re controlling a servo.

The pulse width is much more critical than the frequency

These kind of timings are not possible with Python. In fact, they aren’t really possible with a modern operating system. An interrupt could come in at any time in your control code, causing a longer than desired pulse and a jitter in your servo. To meet the timing requirements we have to enter the fun world of kernel modules. ServoBlaster is a kernel module that makes use of the DMA control blocks to bypass the CPU entirely. When loaded, the kernel module opens a device file at `/dev/servoblaster` that you can write position commands to.

I’ve written a small object oriented layer around this that makes servo control simpler. You can find my library here:

https://github.com/jminardi/RobotBrain

Simple connect the servo to 5v and ground on your Pi and then connect the control wire to pin 4.

The python code is quite simple:

```import time
import numpy as np
from robot_brain.servo import Servo

servo = Servo(0, min=60, max=200)

for val in np.arange(0, 1, 0.05):
servo.set(val)
time.sleep(0.1)```

All you have to do is instantiate a servo and call its `set()` method with a floating point value between 0 and 1. Check out the servo_slider demo on github to see servo control implemented over the network.

# Enaml Pygotham Talk

Here’s the first video available from our Pygotham talk series. As mentioned in an earlier post, you can find the slides in this github repository. Enaml is an open source GUI framework that features declarative syntax and a constraints-based layout solver. The A/V was a little fragmented at the conference, so subsequent videos may feature screencasts rather than live-action video.

Thanks for watching!

# PyGotham Slides

As promised, we have pushed our slides to a public github repository. There may be some updates in the near future (i.e., the parallel python slides are not yet available but all the code examples are there). We will also post videos of the sessions themselves later this week. Many thanks for your patience!

# PyGotham: In Their Own Words

PyGotham is officially over. Many thanks to all the volunteers and organizers for working so hard to make PyGotham a success! Many thanks as well to those of you who decided to attend the Enthought track. We hope we were able to help you solve at least a few of your GPU/Parallel Python/UI/visualization problems. Please don’t hesitate to contact us with any follow-up questions. Finally, a special thank you to Chris Mueller for joining us as a special guest! Your Disco/MapReduce talk was great!

For those of you looking for copies of the slides etc, please stay tuned to this blog. We will be aggregating the materials and will provide a link once we find a home for them.

In the meantime, we hope you enjoy the brief recap video above. The featured researchers, Kate and Michelle, work on macro-molecular proteins at Columbia and are not married to or related to any Enthought staff (as far as I know). Enthought values its relationship with the academic community (come visit us at Scipy!) and we are always happy to see scientists using our tools.

# Just released! EPD 7.3 plus beta version of EPD 8.0

Today we have for you not just one, but two exciting EPD releasesan update of EPD to 7.3 and a beta release previewing new features coming in EPD 8.0.

The EPD 7.3 update adds several new packages including Shapely, openpyxl, and a new package from Enthought named Enaml.  Enaml is a new package for rapidly building UIs using a very “Pythonic” declarative language heavily inspired by Qt’s QML langage.

EPD 7.3 also includes a host of package updates, including adding OpeNDAP support to the NetCDF4 package. Overall over 30 packages have been updated, including Cython, IPython, pandas, basemap, scikit-learn, Twisted and SQLAlchemy.

EPD 8.0 beta takes all that we know and love in EPD 7.x and adds an all-new graphical development and analysis environment.  The new GUI is focused on providing a fast, lightweight interface designed for scientists and engineers.  Some of the key features are:

• A Python-centric text editor including tab-completion plus on-the-fly code analysis.
• An interactive Python (IPython) prompt integrated with the code editor to enable rapid prototyping and exploration.
• A Python package manager to make is easier to discover, install, and update packages in the Enthought Python Distribution.
• Integrated documentation, both on the GUI itself and standard online documentation.

Which version should you install?  EPD 7.3 is the current production release and has the most testing behind it.  If you want to try out EPD 8.0 beta we would love to hear what you think.  EPD 8 is designed to work with earlier versions so once you install the GUI you can either setup a new EPD environment or tell it to use your existing one.  And don’t worry, it’s safe — it won’t modify your existing EPD.

As always, if you have an existing EPD 7.x install that you want to keep you can update all of the Python packages to EPD 7.3 by running the command “enpkg epd” from the command line.  Or, if you have installed the EPD 8 GUI, just open the package manager, select the ‘EPD’ package and click ‘Install’.  It will update you EPD 7.x environment for you.

Any comments, questions, complaints, or compliments on the beta release can be sent to beta-feedback@enthought.com.

# Enthought at PyGotham: June 8th & 9th

To the PyCluster!

Enthought is a proud sponsor of the second annual PyGotham conference in New York City (June 8th and 9th). As part of our commitment, we are also offering a High Performance Python track that will illustrate how to build applications and utilize parallel computing techniques with various open source projects. Stayed tuned for more details as they become available.

Here’s the lineup so far:

• Python with Parallelism in Mind. Rarely does code just happen to be “embarrassingly parallel.” We will discuss some simple rules, structural changes, and diagnostic tools that can help optimize the parallel efficiency of your code. This session will also introduce several common parallel communication technologies that can lower the barrier to parallel computing.
• GPU Computing with CLyther. GPU computing has come a long way over the past few years but still requires knowledge of CUDA or OpenCL. Similar to Cython, CLyther is a Python language extension that makes writing OpenCL code as easy as Python itself.
• MapReduce with the Disco Project. MapReduce frameworks provide a powerful abstraction for distributed data storage and processing. Our friend, Chris Mueller, will talk about the Disco Project, a refreshing alternative to the Hadoop hegemony that uses Python for the front-end and Erlang for the back-end. More importantly, he will discuss when a MapReduce framework makes sense and when it doesn’t.
• Interactive Plotting with Chaco. Most “big data” problems don’t stop with distributed computation. You have to render your results in a way that a larger audience can understand. Chaco is an open source library that helps developers generate performant, interactive data visualizations.
• Declarative UIs with Enaml. Enaml is pythonic UI development done right. Enaml shares Python’s goals of simplicity, conciseness and elegance. Enaml implements a constraint based layout system which ensures that UI’s built with Enaml behave and appear identical on Windows, Linux and OSX. This introduction to Enaml will get you started on the path of writing non trivial UI’s in an afternoon.
• Tie It Together: Build An App. In an updated version of his Pycon talk, Jonathan Rocher ties together time series data — from storage to analysis to visualization — in a demo application. We’ll also walk through a more computationally demanding application to illustrate concepts introduced in the previous talks.

Look forward to seeing everyone there!

# Yet Another Pycon Recap

It’s been a while since the Enthought blog was updated with something other than the odd EPD release announcement. Pycon would have been a good time to recommit ourselves to blogging, but of course technical difficulties with the blog threw a wrench into that plan.

Pycon recaps are now all over the internet and it seems silly to review talks that are readily available on pyvideo.org. Pycon 2012 does mark something of a turning point, however. Enthought has been involved with the Python community for some time. In fact, it came out that Eric Jones, Enthought’s CEO, has been to all 10 Pycons! How do ya like them apples!? In that time, the Python community has grown from a small rag-tag group of rebels into a very large and shiny unicorn.

The latest Pycon was the slickest iteration to date. Some of the old Pycon hands were a bit surprised at the step function upward in expo hall booth quality. It was a veritable cornucopia of booth lounges, t-shirts, and other swag. Recruiting has become much more of a focus as Python has entered the mainstream. The sheer number of people involved has grown more daunting as well (at least for the introverts among us). The YouTube party proved, however, that some things remain the same (can you guess what it is?).

Nevertheless, “community” remained one of the central themes of the conference and we are certain that the next couple of years will offer some interesting developments as programmers push the Python envelope further (e.g. PyPy, domain specific languages, etc.).

Enthought contributed in its own small way. Jonathan Rocher talked about “Storing, manipulating, and visualizing time series data using open source packages” in his Pycon presentation. Enthought staff participated in a number of BOF sessions and Chris Colbert managed to squeak in his lightning talk on Enaml, a domain specific language for declarative UIs. A slightly longer version of his lightning talk is included below for those of you looking to simplify your UI development.

All in all, Santa Clara was a gracious host and we look forward to seeing everyone again next year!