Hacking Raspberry Pi (2014)
Part IV. Hacking the Raspberry Pi
Chapter 20. Raspberry Pi and the Gertboard
Fans of the Gertboard claim that the device is the ultimate expansion board for the Raspberry Pi. Having spent quite a bit of time with the Gertboard, I can tell you that there is indeed substance to that claim.
Gert van Loo (pronounced van LOW) is a Broadcom engineer who also happens to be one of the principal designers of the Raspberry Pi. As I’m sure you can correctly guess, Gert also invented the Gertboard.
Formally defined, the Gertboard is an expansion board, also called a daughterboard, that connects to the Raspberry Pi GPIO headers and gives you instant access to a tremendous variety of input/output options.
You can look at the Gertboard as an activity center or toybox with which you can experiment with motors, switches, buttons, and even an onboard Arduino microcontroller.
Basically, the Gertboard extends the Raspberry Pi to the real world, allowing you to sense temperatures, detect sounds, drive motors, and so forth.
Take a look at Figure 20.1 and the following descriptions for a tour of the PCB’s major components.
FIGURE 20.1 The Gertboard is a multipurpose expansion board for the Raspberry Pi.
1: 12 LEDs
2: 3 momentary button switches
3: Motor controller
4: 6 open collector driver inputs
6: Atmel ATmega chip
7: 10-bit Analog-to-Digital and 8-bit Digital-to-Analog converters
The L6203 motor controller drives brushed DC physical motors, including servos and steppers.
The ULN2803a open collector drivers enable you to turn devices on and off, especially those that use a different voltage than the Gertboard itself or those that use more current than the Gertboard can supply.
The Atmel ATmega 328P AVR microcontroller gives you built-in Arduino prototyping capability. One important note about this on-board Arduino chip is that it runs at 3.3V instead of the standard 5V Arduino voltage.
The MCP4801 Analog-to-Digital (A2D) and MCP3002 Digital-to-Analog (D2A) converters, as you’d expect, enable you to process both analog as well as digital audio signals. This hardware is especially useful if you want to, for instance, detect an input volume for an alarm system.
You learn more about the LEDs, button switches, and GPIO pins momentarily. In the meantime, you are probably wondering where you can purchase a Gertboard.
Originally, the Gertboard was sold in an unassembled state that required soldering. Fortunately, Farnell/Element 14 now sells an assembled model that is ready to rumble for $49 USD, as of this writing. Go purchase a Gertboard at http://is.gd/mnQiHJ.
The assembled Gertboard is called “revision 2” and is physically much different (and improved) from revision 1. For instance, the revision 1 didn’t have an Arduino-compatible Atmel controller, and the board was much more cluttered than the revision 2 model.
Gert himself posted an excellent walkthrough of the Gertboard revision 2 changes in a video on his YouTube channel at http://is.gd/ArQfMK.
Anatomy of the GPIO
The Raspberry Pi General Purpose Input/Output (GPIO) is a 26-pin expansion header that is marked on the PCB as P1 and employs a 2x13 copper pin strip. I provide the GPIO pinout in Figure 20.2.
FIGURE 20.2 The Raspberry Pi GPIO pinout
The pins that you see here are arranged into four basic functionality groups:
2 +3.3V voltage pins
2 +5V voltage pins
5 Ground pins
17 GPIO pins (access to I2C, SPI, and UART)
Raspberry Pi PCBs fabricated after September 2012 are called “revision 2” boards. As it happens, the Foundation changed the function of three GPIO pins between revision 1 and revision 2; for more information, read the article at the Embedded Linux Wiki (http://is.gd/CNl2JC).
The bottom line, friends, is that unless you’re using Ethernet, the GPIO represents the only way to interface your Raspberry Pi with other device hardware. The GPIO header pins are amazingly flexible; they can be reprogrammed to support input or output, and they can be selectively enabled or disabled.
One important note that I’ve mentioned before that bears repeating: although the GPIO has two 5V pins, the GPIO voltage levels are tolerant only of 3.3V signals, and there is not built-in overvoltage protection on the Raspberry Pi. Consequently, if you are not careful you can fry your Pi.
The 5V pins at P1-02 and P1-04 on the Model B board support a maximum current draw of 300mA.
The official name for the Raspberry Pi GPIO is “The GPIO Connector (P1).” Individual pins on the GPIO header are referred to with the P1 prefix; for instance, P1-01, and so forth.
Okay—enough background information. Let’s connect the Gertboard to your Raspberry Pi and begin some serious experimentation!
Connecting Your Gertboard and Raspberry Pi
The Gertboard connects to the Raspberry Pi pin-for-pin by using the GPIO headers. You can either (carefully) mount the Gertboard directly on top of the Pi board, or you can use a 26-pin ribbon cable. You can see a Gertboard/Raspberry Pi sandwich in Figure 20.3.
FIGURE 20.3 The Gertboard connects to the Raspberry Pi board by using the GPIO header.
It’s important to be careful when you connect the Gertboard and the Raspberry Pi. You need to line up every male GPIO pin on the Pi with the corresponding female socket on the underside of the Gertboard. To make this process simpler, you can use the plastic standoffs that ship with the Gertboard to create a more stable surface for the board.
If you want to use a GPIO ribbon cable to make the connection, then you need not only the cable (https://www.modmypi.com/gpio-accessories/ribbon-cables-and-connectors/raspberry-pi-GPIO-assembled-rainbow-ribbon-cable-and-connectors), but also a female-to-male converter (https://www.modmypi.com/gpio-accessories/gpio-header-extenders/26-Pin-GPIO-Shrouded-Box-Header).
Note: On Jumpers and Gender
With jumper wires, or any connection cable for that matter, the male end of one wire or cable inserts into the female (recessed) end of another wire or cable. As you might surmise, this gender-related nomenclature is intimately associated with human reproduction.
Now about power. As long as your Raspberry Pi power supply can give at least 1A, you can power the Gertboard directly from the Pi. The incoming power from the Pi operates at 5V, and the Gertboard uses either 5V or 3.3V depending on which components you use.
In practice, we make connections within the Gertboard and between the Gertboard and the Raspbery Pi by using the straps and jumpers included in the assembled Gertboard kit.
The female-to-female straps enable you to connect pins located in different locations on a board or between boards. By contrast, shunt-type jumpers connect immediately adjacent pins. I show you what these connectors look like in Figure 20.4.
FIGURE 20.4 Traditional shunt-type jumpers along with several types of jumper wire straps (male-to-female, female-to-female, and male-to-male)
Now I’m about to save you a lot of troubleshooting time: Make sure to place a jumper on the two J7 header pins, as shown in Figure 20.5.
FIGURE 20.5 You can add 3.3V of power to the Gertboard components by adding a jumper to the two pins of header J7. The J7 header has three pins, and the jumper covers the top two when the Gertboard is viewed “right-side up.”
By adding this jumper to the Gertboard, you allow 3.3V of power to flow to all of the Gertboard’s components.
Installing the Testing Software
Gert wrote a suite of small C programs that test various Gertboard components. However, we’ve focused on Python in this book, and I’ll continue that here by using the Python Gertboard code modules.
Note: For You C Programmers
To be honest, Gert’s C test suite accesses the Gertboard hardware more directly than does the Python test suite. If you want to download the C code, feel free to do so at http://is.gd/PuS9FU.
The Python test suite was created by Alex Eames of Raspi.TV. Alex wrote the software in Python 2.7, but you’ll recall that Raspbian includes both Python 2 as well as Python 3.
To access Alex’s code in its entirety, you need to have the RPi.GPIO and WiringPi libraries installed. Raspbian, as of September 2012, includes the RPi.GPIO library by default, but you need to install WiringPi (http://wiringpi.com/) yourself. Take a moment and run the following commands from a shell prompt on your Raspberry Pi:
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install python-dev python-pip
sudo pip install wiringpi
Note: GPIO Libraries
The RPi.GPIO and WiringPi libraries both perform the same actions; namely, allowing programmatic access to the Raspberry Pi GPIO header. Alex Eames wrote versions of his Python Gertboard test suite to accommodate both libraries because neither library offers a fully complete set of capabilities. You can read a nice discussion of RPi.GPIO versus WiringPi at the Raspberry Pi forums at http://is.gd/SGAFNp and http://is.gd/wJ1qfb.
Task: Enabling SPI on Your Raspberry Pi
Some of the scripts, notably atod.py, dtoa.py, and dad.py, require that you enable Serial Peripheral Interface (SPI) on your Pi. You can take care of that prerequisite by performing the following steps from a shell prompt on your Raspberry Pi (the Gertboard does not have to be connected at this point although there is no harm done if it is:
1. Open the raspi-blacklist.conf file.
sudo nano /etc/modprobe.d/raspi-blacklist.conf
2. Comment out the following line in the configuration file with a # such that it appears like this:
Performing this action prevents SPI from being disabled on your Raspberry Pi.
3. Save your work, close the file, and reboot:
4. After the reboot, install Git and the Python SPI wrapper:
sudo apt-get install git
git clone git://github.com/doceme/py-spidev
sudo python setup.py install
Although the previous procedure was a bit tedious, the joy that you’ll receive in accessing the Gertboard’s D-to-A and A-to-D converters should make your effort worthwhile.
Now let’s turn our attention to loading the Python Gertboard test suite.
Task: Installing the Python Gertboard Test Suite
Perform the following steps from a shell prompt on your Raspberry Pi:
1. Get the library from Raspi.tv, unpack the ZIP file, and navigate into the extracted folder:
2. Run a directory listing to view the listing of Python scripts and then check out the informative README text file:
ls -l *.py
3. Now that the scripts are unpacked, you can run any of them by invoking sudo privileges and the Python 2 interpreter. For instance, try out the RPi.GPIO-based LED testing script:
sudo python leds-rg.py
The script given here won’t do anything yet because you have to wire up the Gertboard appropriately. We get to that in just a moment.
You can see that Alex wrote two versions of each script file. The -rg file name designation denotes the RPi.GPIO library, while the -wp suffix represents the WiringPi library. Here is a brief rundown of each script’s purpose; note that I removed the -rg and -wp suffixes and added a generic xx placeholder to the script names for clarity:
atod.py: Tests the analog-to-digital converter
butled-xx.py: Tests the button switches and LEDs
buttons-xx.py: Tests the button switches
dad.py: Tests both analog-to-digital and digital-to-analog
dtoa.py: Tests the digital-to-analog converter
leds-xx.py: Tests the LED switches
motor-xx.py: Tests the motor
ocol-xx.py: Tests the relay switches
potmot.py: Tests the analog-to-digital switch and the motor
Testing the LEDs
Your first test lights up the light emitting diode (LED) panel on the Gertboard. You can use either the leds-rg.py or the leds-wp.py script in this case; the RPi-GPIO and WiringPi libraries can both handle this exercise with no problem.
If you examine the source of the leds-rg.py script, you see that Alex documented it pretty well, including giving abbreviated directions for how to wire up the Gertboard. Check out the first few lines:
pi@raspberrypi ~/GB_Python $ sudo python leds-rg.py
These are the connections for the Gertboard LEDs test:
jumpers in every out location (U3-out-B1, U3-out-B2, etc)
GP25 in J2 --- B1 in J3
GP24 in J2 --- B2 in J3
GP23 in J2 --- B3 in J3
GP22 in J2 --- B4 in J3
GP21 in J2 --- B5 in J3
GP18 in J2 --- B6 in J3
GP17 in J2 --- B7 in J3
GP11 in J2 --- B8 in J3
GP10 in J2 --- B9 in J3
GP9 in J2 --- B10 in J3
GP8 in J2 --- B11 in J3
GP7 in J2 --- B12 in J3
(If you don’t have enough straps and jumpers you can install
just a few of them, then run again later with the next batch.)
When ready hit enter.
In this documentation, the Bs and GPs refer to marked locations on the Gertboard. Don’t worry—Gert himself provides excellent board diagrams that show exactly where you should put the jumpers and straps for each of the tests in his suite.
To view the wiring diagram for this test (and for all the other tests, for that matter), download and view the Gertboard user manual at http://is.gd/dOWlUd. To save you the download, you can see the wiring schematic in Figure 20.6 as well.
FIGURE 20.6 The wiring diagram for Gertboard LED test
Figure 20.7 shows you what my lab setup looks like while the test is running.
FIGURE 20.7 My Gertboard/Raspberry Pi setup for the LED test. I hooked up only the first six LEDs.
You need to use sudo when you run the script, and remember that these scripts were written in Python 2, so make sure you invoke the Python interpreter instead of python3.
When you run the script, observe that the Gertboard’s LEDs flash in three discrete patterns. Don’t worry if you don’t have enough straps and jumpers to wire all 12 of the LEDs; hook up as many or as few as you want, and the script will ignore any unconnected LEDs.
Note: Power On or Power Off?
I’m sure you’re wondering, “Do I need to unplug the Raspberry Pi every time I adjust a strap or jumper on the Gertboard?” Although the politically correct answer is yes, I have experienced no strange behavior, nor have I damaged either the Gertboard or the Raspberry Pi by moving from test to test while keeping both boards powered up and online.
To customize the behavior of the LED flashes, open the script in nano or your favorite text editor and play around with the led_drive() function; this is the primary “engine” of the script.
Specifically, the reps parameter defines how many times to run the test. The multiple parameter specifies whether or not to switch off an LED before proceeding to the next one. Finally, the direction parameter defines, well, the directionality of the LED actions, either left-to-right or right-to-left.
Thus, to run the test 10 times in the reverse direction, change the led_drive definition to match the following:
led_drive(10, 0, ports_rev)
The LED test that we just finished tested only the Gertboard’s ability to render output. By contrast, the button/LED test enables you to send the output of a button press to a particular LED as input.
For this test, use the butled-rg.py script because, as of this writing, the test works only with the RPi.GPIO libraries. The file name here is illustrative; it stands for but(ton) and, of course, LED.
The wiring for this test is more straightforward than for the LED test (by which I mean the test requires fewer straps and shunt jumpers). You can view the schematic in Figure 20.8.
FIGURE 20.8 The wiring diagram for Gertboard Input/Output test
Run the test by issuing the command
sudo python butled-rg.py
You see output on your screen as you press the S3 button on the Gertboard, and you also see the BUF6 LED respond to each button press. The screen output cycles between binary 11 (button not pressed, 3.3V voltage (HIGH state) and binary 00 (button pressed, 0V current, LOW state).
I challenge you to figure out how to activate the other two button switches and link them to two additional LEDs. Have fun!
A Couple Quick Breadboarding Exercises
In Chapter 3, “A Tour of Raspberry Pi Peripheral Devices,” you learned what a breadboard is and how important the tool is in prototyping hardware. I wanted to devote a bit of space in this book to showing you a couple of breadboarding experiments that you can undertake with your Raspberry Pi.
Both experiments execute as simple a task as possible: lighting an LED. However, I want to show you how you can run the experiment by using a breadboard and the naked Raspberry PI GPIO pins as well as how you can do the same thing with the Adafruit Pi Cobbler that I told you about inChapter 3.
Accessing the GPIO Pins Directly
Let’s begin by looking at a shopping list of parts that you need to complete this introductory prototyping experiment:
1 standard breadboard
1 resistor in the 270–330 ohm range
2 male-to-female jumper straps
You can find all of these parts at your local RadioShack or electronics shop. Alternatively, I’ve gotten a lot of mileage out of electronics prototyping kits. To that point, here are some suggestions I’ve found useful:
Sparkfun RedBoard Breadboard Kit (http://is.gd/FbYgZ5)
RadioShack Breadboard and Jumper Wire Kit (http://is.gd/XGEBWz)
MakerShed Mintronics Survival Pack (http://is.gd/UMcR9O)
Note: Sometimes “Dish” Is Not Related to Gossip
Adafruit sells the wonderful Pi Dish ($22.50, http://is.gd/n4TmjO) that enables you to secure a Raspberry Pi and a standard breadboard in an attractive, clear, and sturdy package. An accessory like this makes Raspberry Pi breadboarding infinitely cleaner and easier than dealing with free-floating PCBs, straps, and jumpers.
Task: Lighting an LED Directly from the GPIO
In this procedure, pull current from GPIO pin #1 at 3.3V and feed it through an LED mounted on the breadboard. The resister is mounted in the same circuit; the higher the resistance value, the dimmer the light shines. If your resister is too small, you will burn out the LED bulb. Finally, the resistor bleeds off excess current to the ground rail on the outside rim of the breadboard.
1. Turn off your Raspberry Pi.
2. Carefully press the resistor and male-to-female jumper straps in place. You can see the wiring diagram in Figure 20.9.
FIGURE 20.9 The wiring diagram for our first breadboarding experiment
Note: How I Created My Wiring Diagrams
To create these nifty wiring diagrams, I used a wonderful piece of open source software called Fritzing (http://is.gd/i17V7t). With a few mouse clicks, you can document your prototypes in an eye-appealing and accurate way. What’s more, Adafruit publishes a Github repository with Raspberry Pi and Pi Cobbler Fritzing parts (http://is.gd/ZLCdPk). Great stuff!
3. The LED has a longer leg and a shorter leg. The longer leg is the positive terminal and goes in the same breadboard row as the 3.3V jumper. The shorter leg is the negative terminal and goes in the same row as the resistor.
4. Power on the Raspberry Pi. If everything is hooked up correctly, you should see the LED light up immediately.
Let’s extend this experiment such that you gain control over the illumination state of the LED. To do this, you again access the WiringPi libraries.
Physically, all you have to do is relocate the female jumper pin currently plugged into GPIO #1 to GPIO pin #11.
With that done, you need to perform a little bit of housekeeping with the WiringPi libraries to send commands to the Raspberry Pi GPIO pins directly.
Download and then compile the WiringPi executable code:
git clone git://git.drogon.net/wiringPi
git pull origin
Awesome! Now you can stay in the current directory and issue GPIO commands to your heart’s content. For instance, try the following:
gpio mode 0 out
gpio write 0 1
gpio write 0 0
You should find that the gpio write 0 1 command turned the LED on and that the gpio write 0 0 line turned the LED off. It’s like you’re turning on a faucet: when you send 3.3V out of programmable GPIO #11 pin into the LED, the electrical energy is consumed and emitted as light.
Accessing the GPIO Pins via the Pi Cobbler
The Adafruit Pi Cobbler (http://is.gd/B1U0bq) represents a more elegant way to make the Raspberry Pi GPIO pins accessible to you and your projects. Instead of wiring individual jumpers from the GPIO pins to the breadboard, you can break out from the GPIO header directly to the breadboard and then access GPIO from there.
Adafruit sells the Pi Cobbler either unassembled or assembled; I leave it up to you and your tolerance for pain (just kidding) in deciding which product to purchase. In addition to the Pi Cobbler breakout IC, you also get a ribbon cable.
To mount the Pi Cobbler, you first must connect the cable to the Cobbler board itself. Adafruit was nice enough to add a notch in the 26-pin ribbon cable, so it is impossible to insert the cable into the Cobbler incorrectly.
You can potentially get into trouble by inserting the other end of the ribbon cable into the Raspberry Pi GPIO header, though. Locate the colored edge wire of the ribbon cable; this is pin #1 and needs to be inserted into the GPIO on the side closest to the SD card slot and where P1 is marked on the Raspberry Pi board.
You also need to take care to insert the Pi Cobbler in the breadboard such that the Cobbler straddles the bridge or center line. Be sure to press the Cobbler all the way into the breadboard. You can see a close-up of my installed Pi Cobbler in Figure 20.10.
FIGURE 20.10 The Pi Cobbler is simultaneously connected to the breadboard and the Raspberry Pi and serves to extend the GPIO to the board. The markings above each Cobbler pin match each corresponding GPIO pin on the Raspberry Pi.
Whew! Now that you have that out of the way, what can you actually do with the Pi Cobbler?
Well, look closely at the perimeter of the Cobbler—you should see markings that correspond to each of the 26 pins of the Raspberry Pi GPIO.
You can easily repeat your initial LED experiment by inserting male-to-male (note that you need male ends when your connection begins and ends on the breadboard) jumper straps in the same breadboard row as the corresponding GPIO header.
The only change I make, as noted in Figure 20.11, is that I used a GPIO ground pin on the same side of the breadboard as the power pin.
FIGURE 20.11 A replication of the earlier breadboarding experiment, this time by using the Pi Cobbler breakout board
Programming the Atmel Microcontroller
That long, 28-pin DIP you see soldered in next to the left of the Gertboard logo on the PCB is none other than an Atmel AVR ATmega328p microcontroller, the same chip that you experimented with in the previous chapter.
Note: Subject to Parts Availability...
Take a moment to read the identification information on the surface of your Gertboard’s Atmel chip. Gert states that due to parts availability, the Gertboard may be equipped with either the ATmega 328 or 168.
This means you can perform Arduino experiments by compiling sketches on the Raspberry Pi and sending them to the ATmega directly. Now then, recall that the Arduino operates at 5V, and the Raspberry Pi operates at 3.3V. The upshot of this situation for our purposes is that the Gertboard’s ATmega runs at a slower clock speed (12MHz instead of 16MHz).
Thus, if you plan to reuse some of your sketches from Chapter 19, “Raspberry Pi and Arduino,” you need to adjust any references to +5V or you may very well fry the Gertboard’s ATmega chip. You also may need to adjust the timing of your sketch code to account for the Gertboard’s slower clock speed.
Task: Preparing Your Arduino Environment
I covered installing the Arduino IDE in Chapter 19. However, I want to give you the complete procedure now in case you haven’t done any work with the Arduino UNO yet.
Perform the following tasks from a terminal prompt on your Raspberry Pi:
1. Start by downloading and installing the Arduino IDE:
sudo apt-get install -y arduino
2. Use AVRDUDE to help you upload your Arduino sketches to the AVR microcontroller on the Gertboard.
sudo dpkg -i avrdude_5.10-4_armhf.deb
sudo chmod 4755 /usr/bin/avrdude
3. The bad news is that there are several steps involved in completing the Raspberry Pi-Gertboard Arduino setup. The good news is that Gordon Henderson, a British computer consultant with jaw-dropping expertise with the Raspberry Pi, Gertboard, and Arduino environments, graciously created a script that automates these steps. Check out Gordon online at http://is.gd/7SPmYJ.
chmod +x setup.sh
4. After the script completes, you are prompted to reboot your Raspberry Pi. Do that.
5. Initialize the ATmega chip. Make sure your Gertboard is installed and attach the jumper wires as shown in Figure 20.12.
FIGURE 20.12 The wiring diagram to initialize the ATmega chip on the Gertboard
6. Issue the “magic” initialization command:
You see the following output:
Initialising a new ATmega microcontroller for use with the Gertboard.
Make sure there is a new ATmega chip plugged in, and press
.. 1 for an ATmega328p or 2 for an ATmega168: 1
7. If you have the ATmega 328 on your Gertboard, type 1 and press Enter. (Type 2 if you have the ATmega168.) If all goes well, you’ll see the following output:
Initialising an ATmega328p ...
Looks all OK - Happy ATmega programming!
8. You’re almost home-free. You just have a bit of configuration to do in the Arduino IDE itself. First, fire up the IDE:
9. In the Arduino IDE, Click Tools, Board and select Gertboard with ATmega328(GPIO) from the flyout menu.
10. Next, click Tools, Programmer and select the Raspberry Pi GPIO option.
To test functionality by using the built-in Blink sketch, you first need to attach a jumper strap from location PB5 on the left side of the Gertboard to one of the buffered LED outputs. (I use BUF6 as a matter of practice.)
After you’ve connected the wire, go back to the Arduino IDE and click File, Examples, 01.Basics, Blink, and then click the Upload button (or click File, Upload using Programmer) to send the sketch to the ATmega chip.
You should see the BUF6 LED begin to blink slowly.
Final Thoughts, and Thank You
Well, congratulations! You’ve reached the end of this book. We’ve certainly come a long way, haven’t we?
By way of a take-home message, I encourage you to stay current with all things Raspberry Pi-related by plugging into and participating in the community. The most direct entry points into the Raspberry Pi community are as follows:
Official Raspberry Pi Community Forum: http://is.gd/6nBR5Z
Google+ Raspberry Pi Forum: http://is.gd/jGajWj
Stack Exchange: Raspberry Pi: http://is.gd/hWh8EK
RPi Community Links at eLinux.org: http://is.gd/sN9O4g
If you completed even the majority of tasks in this volume, then you have an excellent grasp of the fundamentals of hardware and software hacking. Should you have any questions, or if you want to share your experiences all the way, I’m all ears. You can reach me directly email@example.com.
Thank you so very much for purchasing this book and for learning more about the Raspberry Pi. It is people like you who keep information technology relevant and growing over time.