When you put together one of our interface boards you’ll see that it breaks out the GPIO pins into their own header and labels them 0 to 7. Our GPIO library numbered Pins 0..23, after the header pins on the Raspberry Pi. That’s pretty awkward in practice so we’re experimenting with ways to make it easier to write programs that work with broken out GPIO headers.

Our current approach is to replace the Pin type with two pin classes: GPIOPIn and HeaderPin. A GPIOPin is created with a pin number from 0 to 7 that identifies the pin on the interface board. A HeaderPin is created with a pin number from 0 to 23 that identifies the pin on the Pi’s header.

For example:

#!/usr/bin/python3

import sys
from time import sleep
from quick2wire.gpio import GPIOPin, In, Out

led = GPIOPin(1, direction=Out)
button = GPIOPin(0, direction=In)

while True:
      led.value = button.value
      sleep(0.1)

To ensure that existing code keeps working, we define Pin as a synonym of HeaderPin. But when we’ve found an approach that works well we’ll deprecate Pin and eventually remove it from the API.

I’ve just come home after a great session in Norwich. One of the most enjoyable things about this sort of meeting is that you get a wonderful range of perspectives on the Pi. Here’s one.

Nev Young explained that he’d already recovered the price of his Pi in reduced electricity costs. His web server (please don’t all visit at once!) now runs on a Raspberry Pi, consuming about two watts instead of three hundred. That’s the way to save the planet one server at a time. Brilliant!

There were lots of other interesting people there. Too many to mention them all, but they included a solicitor who runs archlinux on his laptop, and is teaching himself Python on his Pi, a retro-game-meister, a developer who is working on what could be a uniquely extensible social game, and of course @stevedp – a fellow Python developer and Pi enthusiast who manages the http://norwichrpi.org/ website.

I did our blinken-bar led demo, but with a new twist. We’ve just published the first version of a library for the PCF8591, which is the chip at the heart of our I2C analogue board. We’ve hooked one up to a photocell and written a little Python program to display the light level on a Bar LED. I have to admit to a childish pleasure in seeing the LED respond as I wave my hand above the board.

Here’s our post about the demo with video and code, and a report from @norwichrpi (with photos) here.

I was made to feel very welcome, and will be heading back when we have the next lot of boards to show.

Most of our users started out with revision 1 of the Raspberry Pi, but a growing number have revision 2 boards, and some have both.

A few things changed in revision 2, including GPIO pin numbering and the I2C interface.

Until yesterday our GPIO library did not handle header pin 13 correctly on revision 2 RasPis, and the I2C library required you to specify that you wanted to use I2C bus  1.

We’ve updated the library and those problems should now be a thing of the past.

If you are using the quick2wire-python-api libraries, you will need to pull the new versions from github. If you got to the directory in which you cloned the library, just run git pull from the command line and you should get the new version of the code.

25. November 2012 · 16 comments · Categories: API, GPIO

Quick2Wire’s Python GPIO library allows your program to be notified when something interesting has happened to a device attached to a GPIO pin. Instead of repeatedly checking the pin, an application can wait for the pin to trigger an event as soon as its state changes. Interrupt-driven GPIO also works with the Python epoll library, so you can integrate your GPIO code with other core system objects such as network sockets and files.

Polling for changes

Traditional GPIO programming works by polling the state of the pins. You write a “busy loop”, continually checking the status of a pin until you see the signal you want.

pin = pins.pin(0, direction=In)
while True:
     if pin.value == 1:
         handle_pin_1()

This code is fine for dedicated devices, such as an Arduino, but is not appropriate for the Pi because it monopolizes the Pi’s processor. Linux will struggle to give enough processor time to other tasks, such as serving web pages or reading from the command line. Swapping between tasks will result in degraded performance for the entire system.

An obvious solution is to check the value of the pin less frequently:

pin = pins.pin(1, direction=In) 
while True: 
    while pin.value == 0: # Are we there yet? 
        sleep(1) # Take a quick nap 
        handle_pin_1()

This improves the responsiveness of the Pi, but it’s still problematic. How long should it sleep? Too little and there will still be performance problems, too long and the application might not respond promptly to a pin event. More interestingly, what if you’re on waiting for more than one input? You’ll need to expand your loop to check each pin in turn:

pin1 = pins.pin(0, direction=In) 
pin2 = pins.pin(1, direction=In) 
while True: 
    if pin1.value == 1 
        handle_pin_1() 
    if pin2.value == 0 
        handle_pin_2() 
    sleep(1)

There’s a better solution, but it requires a new programming model:

Using Python’s epoll API with GPIO

GPIO interrupts allow an application to use epoll to wait for a GPIO events instead of continually checking the value of the pin in a busy loop  Epoll is a Linux facility for efficiently handling event notifications. Quick2Wire’s GPIO Pins integrate into Python’s epoll library with a little extra code:

import select 
pin1 = pins.pin(0, direction=In, interrupt=Rising)
pin2 = pins.pin(1, direction=In, interrupt=Falling)

epoll = select.epoll() 
epoll.register(pin1, select.EPOLLIN | select.EPOLLET) 
epoll.register(pin2, select.EPOLLIN | select.EPOLLET) 
with pin1, pin2
    while True: 
        events = epoll.poll() 
        for fileno, event in events: 
            if fileno == pin1.fileno(): 
                handle_pin_1() 
            if fileno == pin2.fileno(): 
                handle_pin_2()

This might look confusing if you aren’t used to epoll, so we’ll step through the code:

pin1 = pins.pin(0, direction=In, interrupt=Rising)
pin2 = pins.pin(1, direction=In, interrupt=Falling)

Notice the new parameter to the Pin constructor. Adding this parameter enables interrupts on the pin, which will be used to wake your application. The pin can be configured to wake when high (‘Rising’), low (‘Falling’) or either (‘Both’).

epoll = select.epoll()
epoll.register(pin1, select.EPOLLIN | select.EPOLLET) 
epoll.register(pin2, select.EPOLLIN | select.EPOLLET)

Here we create an epoll object and register our pins. The flags tell epoll to wake up whenever there is something to read, but only on “edge triggers”. Unlike the older Linux functions select and poll, epoll can be configured to wake up with either “level triggers” or “edge triggers”. Level triggers (the default) will cause epoll.poll() to return whenever the condition is true. Edge triggers will cause epoll.poll() to return only once after a transition from low-to-high or high-to-low.

while True: 
    events = epoll.poll() 
    for fileno, event in events: 
        ...

Here’s our main loop. Each call to epoll.poll() returns a list of events, one event for each of the registered objects that have been triggered since the previous call. Each event is a pair of the file number for the object being triggered and flags describing the type of event that happened (for example EPOLLIN for an input).

Adding more input types

Python will allow you to register any file descriptor with epoll. Because “everything is a file” in Linux, we can, for example, listen for network sockets and the keyboard in the same loop as our pin.

sock = initialize_socket() 
pin = pins.pin(0, direction=In, interrupt=Both) 
pin.open()
epoll = select.epoll()
epoll.register(sock, select.EPOLLIN)
epoll.register(pin, select.EPOLLIN | select.EPOLLET)
epoll.register(sys.stdin, select.EPOLLIN) 
while True: 
    events = epoll.poll() 
    for fileno, event in events: 
        if fileno == sys.stdin.fileno(): 
            # read from the keyboard (or stdin) 
        if fileno == pin.fileno(): 
            # read from the pin 
        if fileno == sock.fileno(): 
            # read from the socket

For another example of GPIO and epoll, take a look at the Quick2Wire Python epoll example in GitHub.

While we’re waiting for the first interface boards to arrive we’ve been checking out our libraries against the new Raspbian distro.

The latest Raspbian kernel supports I2C and SPI, and today we got all our loopback tests passing. This means we have working Python libraries on Raspbian for GPIO, I2C and SPI.

Raspbian is now the official recommended kernel, so we’re fast approaching the point where a new Pi user can plug in our hardware, install our libraries, run an example and expect everything to work.

At the moment the Python GPIO library needs our gpio-admin library as well as the Python code. Soon we’ll package the two together as a .deb file, which will make things even easier. The gpio-admin and Quick2Wire Python libraries are on github so if you feel like experimenting, clone away and let us know how you get on! The libraries have examples and test code included.

If you want to try out the SPI code, you’ll need to upgrade to the latest Raspbian firmware. The kernel in the current Raspbian image (2012-07-15-wheezy-raspbian) supports I2C but not SPI; you can use Hexxeh’s firmware updater to get a later kernel, which supports both.

There are a couple of other things you’ll need to do: uncomment the two lines in /etc/modprobe.d/raspi-blacklist.conf which stop needed modules from loading, and add a line i2c-dev to /etc/modules to ensure that the relevant i2c module is loaded on boot-up.

Your raspi-blacklist.conf should then look like this:

# don't blacklist spi and i2c by default
# blacklist spi-bcm2708
# blacklist i2c-bcm2708

and  /etc/modules should look like this:

# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.
# Parameters can be specified after the module name.
snd-bcm2835
i2c-dev

PS Things are moving fast. If you want to keep up-to-date with what’s happening here at Quick2Wire, sign up for our free newsletter. Just fill in your email at the top of the page and click sign up. We won’t spam you, and you can unsubscribe at any time.

 

We’re currently testing our Python library for controlling GPIO on the Raspberry Pi. Once it’s ready for prime time we’ll be releasing it on github, like the gpio-admin library on which it relies, under an Open Source License.

We’ve put up a basic demo on YouTube; the first one isn’t that exciting, as one flashing LED looks much like another. We hope to have some prettier videos soon.

Here’s the code that drives the LED:

from quick2wire.gpio import Pin
from time import sleep

out_pin = Pin(12, Pin.Out)
for i in range(0, 10):
    out_pin.value = 1
    sleep(1)
    out_pin.value = 0
    sleep(1)
out_pin.unexport()

The ’12′ used to identify the pin refers to the pin number on the expansion header. You can find a neat diagram of the header here.

As the first trickle of Raspberry Pi computers reach developers, we’re seeing more and more sample code for driving the GPIO pins on the Pi’s expansion port.

We like that – after all, our business is based on the belief that lots of Pi users will want to interact with the physical world, building environmental monitoring stations, test equipment, robots, and projects we can’t even begin to imagine. And to do that they’ll need access to GPIO.

A typical bit of GPIO code does several things:

  • the code starts by exporting the pin you want to use. In effect, this tells Linux that you want control of that pin.
  • then the code sets that pin as an input or output, and reads from or writes to the pin.
  • finally, the code unexports the pin so that it’s available to others.

You’ll find plenty of code examples that do just that. There’s just one problem: all the code we’ve seen has to be run as root, and that’s really, really bad.

The root of all evil

One of the first things you learn when you start using Linux is that the root account is really dangerous. A short command can wipe the entire filesystem, losing all your work and requiring you to build a new SD card image and start again from scratch. Because the root account is so powerful, you should normally log on as an ordinary user (pi, for example) and use the sudo command to elevate your access to root level only when absolutely necessary and only for short tasks that require special privileges. (That’s on debian-based installations; other distros may expect you to do things slightly differently in order to work as root.)

So software that requires you to work as root in order to drive the GPIO pins is, in our opinion, a real no-no.

gpio-admin to the rescue

Now there’s a solution. We’ve created a program called gpio-admin which does two things:

  1. It can export and unexport GPIO pins..
  2. When a pin is exported, access to the pin is granted to users in the gpio group; those users can set the pin as an input or output, and then read from or write to the pin.

Anyone in the gpio group can run gpio-admin once it has been installed. You have to install it as root, but that’s OK; just use sudo for the installation process, and then continue as an ordinary user. (For details, see below.)

In order to make use of an exported GPIO pin, you’ll need to add yourself to the gpio group. We’ll look at how to do that shortly.

There are several ways in which you can configure and use the GPIO pin once it’s been exported. You can do it by typing shell commands, but most users will want to manipulate the GPIO pins under program control. We’re also working on a Python class which you can use in your Python code. The Python class will allow you to configure and use a GPIO pin, and will also invoke gpio-admin as necessary.

The naming of pins

If you want to use GPIO there is another complication lurking in the background.

There are (at least) three plausible ways you can refer to pins on the Pi expansion header.

  1. You can refer to the physical pin number. The pins are numbered from 1-26, and the numbering is well-defined.
  2. You can use the same designation as is used by the Raspberry Pi documentation. There are eight GPIO pins, GPIO0-GPIO7, and other pins that can be used for GPIO called (for example) SDA0 and SCL0. These are normally used for I2C, but can be used for GPIO instead if I2C is not required.
  3. You can use the same designation that is used by Broadcom and the linux kernel. We refer to these as SOC pin numbers. in this numbering system there are 54 GPIO pins numbered from GPIO0 to GPIO53. Not all of these are accessible, and most are not connected to the header in the current design. More may be connected in future hardware revisions.
For now, we are using the SOC pin numbering system for gpio-admin, but will use physical pin numbering for our Python code. We’re expecting almost everyone to use Python, and Python will take care of the mapping from physical pin number to SOC pin numbering.
In the Python code, use the following mappings:

GPIO Header
GPIO0 11
GPIO1 12
GPIO2 13
GPIO3 15
GPIO4 16
GPIO5 18
GPIO6 22
GPIO7 7

Installation

All of this is pretty new, but we’ve released gpio-admin so you can have a play with it if you’re feeling brave.

These instructions assume that you are running the latest debian squeeze image; we have no idea if this code will work on other distributions, and advise you not to try it.

The project is hosted on github, where all sorts of Pi-related things are available. To install gpio-admin on your Pi, you’ll need to install git, if you haven’t done so already, by running sudo apt-get install git-core in a command window.

Then change to a suitable directory and clone the project there. We use a git directory within our home directory for all git-related stuff.

Create the clone by running git clone git://github.com/quick2wire/quick2wire-gpio-admin.git in a command window. That will create a sub-directory called gpio-admin. Run cd gpio-admin to move into that directory.

Next, install the software by running make and then sudo make install in a command window.

Nearly there!

Join the gpio group and run some software.

Now you need to add yourself to the gpio group. Run sudo adduser $USER gpio and then log off and log on again. The group membership won’t take effect until you do.

Now you can make use of the pins:

% gpio-admin export 22
% cat /sys/devices/virtual/gpio/gpio22/value
0
% echo out > /sys/devices/virtual/gpio/gpio22/direction
% echo 1 > /sys/devices/virtual/gpio/gpio22/value

The first command exports pin 22. The pin is initially configured as an input pin. The second command reads the value of the pin: it is zero (low). The third command sets the pin to be an output pin, and the final command sets the value to be 1 (high). If pin 22 is connected to a a voltmeter, you’ll see its voltage go from 0 to 3.3 volts.

The example above uses SOC GPIO 22, which corresponds to header pin 8 on the Raspberry Pi, and that pin is named GPIO 3 in the Raspberry Pi documentation.

Tidy up before you leave

Once you’ve finished, The last thing to do is to unexport the pin so that it’s free for other programs to use. Run gpio-admin unexport 22 and celebrate your first physical computing with the Pi.

What next?

As mentioned above, we’re working on a little Python library that will make it even easier to use GPIO pins under program control. You’ll still need to install gpio-admin, as described above, but your Python program will be able to use objects that, under the hood, handle the gpio-admin calls as well as reading from or writing to GPIO pins.

Credits: Thanks to Nat Pryce for doing the heavy lifting. Nat wrote the gpio-admin code and is developing the Python API.