Raspberry Pi LED Blueprints
上QQ阅读APP看书,第一时间看更新

Introducing Raspberry Pi GPIO

General-purpose input/output (GPIO) is a generic pin on Raspberry Pi, which can be used to interact with external devices, such as sensor and actuator devices. You can see the Raspberry Pi GPIO pinouts in the following figure (source: http://www.element14.com/community/docs/DOC-73950/l/raspberry-pi-2-model-b-gpio-40-pin-block-pinout):

Introducing Raspberry Pi GPIO

To access Raspberry Pi GPIO, we can use several GPIO libraries. If you are working with Python, Raspbian will have already installed the RPi.GPIO library to access Raspberry Pi GPIO. You can read more about RPi.GPIO at https://pypi.python.org/pypi/RPi.GPIO. You can verify the RPi.GPIO library from a Python terminal by importing the RPi.GPIO module, as shown in the following screenshot:

Introducing Raspberry Pi GPIO

If you don't find this library on Python runtime or get the error message ImportError: No module named RPi.GPIO, you can install it by compiling from the source code. For instance, we want to install RPi.GPIO 0.5.11, so type the following commands:

wget https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.5.11.tar.gz
tar -xvzf RPi.GPIO-0.5.11.tar.gz
cd RPi.GPIO-0.5.11/
sudo python setup.py install

Tip

To install and update through the apt command, your Raspberry Pi must be connected to the Internet.

Another way to access Raspberry Pi GPIO is to use WiringPi. It is a library written in C for Raspberry Pi to access GPIO pins. You can read information about WiringPi from the official website http://wiringpi.com/.

To install WiringPi, you can type the following commands:

sudo apt-get update
sudo apt-get install git-core
git clone git://git.drogon.net/wiringPi
cd wiringPi
sudo ./build

Please make sure that your Pi network does not block the git protocol for git://git.dragon.net/wiringPi. This code can be browsed on https://git.drogon.net/?p=wiringPi;a=summary.

The next step is to install the WiringPi interface for Python, so you can access Raspberry Pi GPIO from a Python program. Type the following commands:

sudo apt-get install python-dev python-setuptools
git clone https://github.com/Gadgetoid/WiringPi2-Python.git
cd WiringPi2-Python
sudo python setup.py install

When finished, you can verify it by showing a GPIO map from the Raspberry Pi board using the GPIO tool:

gpio readall

If this is successful, you should see the GPIO map from the Raspberry Pi board on the terminal:

Introducing Raspberry Pi GPIO

You can also see values in the wPi column, which will be used in the WiringPi program as GPIO value parameters. I will show you how to use it in the WiringPi library in the next section.