While the Raspberry Pi is, in essence, a very inexpensive Linux computer, there are a few things that distinguish it from laptop and desktop machines that we usually use for writing email, browsing the Web, or word processing. One of the main differences is that the Raspberry Pi can be directly used in electronics projects, because it has general-purpose input/output pins right on the board, shown in Figure 6-1.
These GPIO pins can be accessed for controlling hardware such as LEDs, motors, and relays, which are all examples of outputs. As for inputs, your Raspberry Pi can read the status of buttons, switches, and dials, or it can read sensors for things like temperature, light, motion, or proximity (among many others).
The best part of having a computer with GPIO pins is that you can create programs to read the inputs and control the outputs based on many different conditions, as easily as you’d program your desktop computer. Unlike a typical microcontroller board, which also has programmable GPIO pins, the Raspberry Pi has a few extra inputs and outputs, such as your keyboard, mouse, and monitor, as well as the Ethernet port, which can act as both an input and an output. If you have experience creating electronics projects with microcontroller boards like the Arduino, you have a few more inputs and outputs at your disposal with the Raspberry Pi. Best of all, they’re built right in; there’s no need to wire up any extra circuitry to use them.
Having a keyboard, mouse, and monitor is not the only advantage that Raspberry Pi has over typical microcontroller boards. There are a few other key features that will help you in your electronics projects:
Being able to read and write data in the Linux filesystem will make many projects much easier. For instance, you can connect a temperature sensor to the Raspberry Pi and have it take a reading once a second. Each reading can be appended to the end of a log file, which can be easily downloaded and parsed in a graphing program. It can even be graphed right on the Raspberry Pi itself!
Packaged in the Raspberry Pi’s Linux distribution is a set of core command-line utilities, which let you work with files, control processes, and automate many different tasks. These powerful tools are at your disposal for all of your projects. And because there is an enormous community of Linux users that depend on these core utilities, getting help is usually one web search away. For general Linux help, you can usually find answers at Stack Overflow. If you have a question specific to Raspberry Pi, try the Raspberry Pi Forum or the Raspberry Pi section of Stack Overflow.
There are many programming languages out there, and embedded Linux systems like the Raspberry Pi give you the flexibility to choose whichever language you’re most comfortable with. The examples in this book use shell scripting and Python, but they could easily be translated to languages like C, Java, or Perl.
There are a few supplies that you’ll need in addition to the Raspberry Pi itself in order to try out these basic input and output tutorials. Many of these parts you’ll be able to find in hobby electronics component stores, or they can be ordered online from stores like MakerShed, SparkFun, Adafruit, Mouser, or Digi-Key. Here are a few of the basic parts:
Solderless breadboard
LEDs, assorted
Male-to-male jumper wires
Female-to-male jumper wires (these are not as common as their male-to-male counterparts but are needed to connect the Raspberry Pi’s GPIO pins to the breadboard)
Pushbutton switch
Resistors, assorted
To make it easier to connect breadboarded components to the Raspberry Pi’s pins, we also recommend Adafruit’s Pi Cobbler Breakout Kit, which connects all the GPIO pins to a breadboard with a single ribbon cable. This eliminates the need to use female-to-male jumper wires. If you go with the less-expensive, unassembled version of the kit, it’s up to you to solder the parts onto the board, but it’s easy to do, and Adafruit’s tutorial walks you through the process step by step.
In Figure 6-2, we’ve labeled each pin according to its default GPIO signal number, which is how you’ll refer to a particular pin in the commands you execute and in the code that you write. The unlabeled pins are assigned to other functions by default.
There’s a handy website created by Phil Howard called Raspberry Pinout which we recommend you bookmark. It’ll show you the Raspberry Pi’s GPIO pins and has tons of reference information about how they can be used.
There are also great products such as RasPiO Portsplus Port ID board, shown in Figure 6-3. It’s a small board that fits over the GPIO pins for the sole purpose of making the pins easy to identify.
The easiest way to use outputs with the GPIO pins is by connecting an LED, or light-emitting diode. You can then use the Linux command line to turn the LED on and off. Once you have an understanding of how these commands work, you’re one step closer to having an LED light up to indicate when you have new email, when you need to take an umbrella with you as you leave your house, or when it’s time to go to bed. It’s also very easy to go beyond a basic LED and use a relay to control a lamp on a set schedule, for instance.
If you’ve never used a breadboard (Figure 6-4) before, it’s important to know which terminals are connected. In the diagram, we’ve shaded the terminal connections on a typical breadboard. Note that the power buses on the left side are not connected to the power buses on the right side of the breadboard. You’ll have to use male-to-male jumper cables to connect them to each other if you need ground and voltage on both sides of the breadboard.
Here are the instructions you should follow:
Using a male-to-female jumper wire, connect pin 25 on the Raspberry Pi to the breadboard. Refer to Figure 6-2 for the location of each pin on the Raspberry Pi’s GPIO header.
Using another jumper wire, connect the Raspberry Pi’s ground pin to the negative power bus on the breadboard.
Now you’re ready to connect the LED (see Figure 6-5). Before you do that, it’s important to know that LEDs are polarized: it matters which of the LED’s wires is connected to what. Of the two leads coming off the LED, the longer one is the anode (or “plus”) and should be connected to a GPIO pin. The shorter lead is the cathode (or “minus”) and should be connected to ground. Another way to tell the difference is by looking from the top. The flat side of the LED indicates the cathode, the side that should be connected to ground. Insert the anode side of the LED into the breadboard in the same channel as the jumper wire from pin 25, which will connect pin 25 to the LED. Insert the cathode side of the LED into the ground power bus.
An easy way to remember the polarity of an LED is that the “plus” lead has had length added to it, while the “minus” lead has had length subtracted from it.
With your keyboard, mouse, and monitor hooked up, power on your Raspberry Pi and log in. If you’re at a command line, you’re ready to go. If you’re in the X Window environment, double-click the LXTerminal icon on your desktop. This will bring up a terminal window.
In order to access the input and output pins from the command line, you’ll need to run the commands as root, the superuser account on the Raspberry Pi. To start running commands as root, type sudo su
at the command line and press Enter:
pi@raspberrypi ~ $ sudo su
root@raspberrypi:/home/pi#
You’ll notice that the command prompt has changed from $
to #
, indicating that you’re now running commands as root.
The root account has administrative access to all the functions and files on the system and there is very little protecting you from damaging the operating system if you type a command that can harm it. You must exercise caution when running commands as root. If you do mess something up, don’t worry about it too much; you can always reimage the SD card with a clean Linux install; however, you’ll lose any customization you made to the operating system, as well as any programs or sketches you wrote.
When you’re done working within the root account, type exit
to return to working within the pi
user account.
Before you can use the command line to turn the LED on pin 25 on and off, you need to export the pin to the userspace (in other words, make the pin available for use outside of the confines of the Linux kernel), this way:
root@raspberrypi:/home/pi# echo 25 > /sys/class/gpio/export
The echo
command writes the number of the pin you want to use (25) to the export file, which is located in the folder /sys/class/gpio. When you write pin numbers to this special file, it creates a new directory in /sys/class/gpio that has the control files for the pin. In this case, it created a new directory called /sys/class/gpio/gpio25.
Change to that directory with the cd
command and list the contents of it with ls
:
root@raspberrypi:/home/pi#cd /sys/class/gpio/gpio25
root@raspberrypi:/sys/class/gpio/gpio25#ls
active_low direction edge power subsystem uevent value
The command cd
stands for “change directory.” It changes the working directory so that you don’t have to type the full path for every file. ls
will list the files and folders within that directory. There are two files that you’re going to work with in this directory: direction
and value
.
The direction
file is how you’ll set this pin to be an input (like a button) or an output (like an LED). Because you have an LED connected to pin 25 and you want to control it, you’re going to set this pin as an output:
root@raspberrypi:/sys/class/gpio/gpio25# echo out >
direction
To turn the LED on, you’ll use the echo
command again to write the number 1 to the value
file:
root@raspberrypi:/sys/class/gpio/gpio25# echo 1 > value
After pressing Enter, the LED will turn on! Turning it off is as simple as using echo
to write a zero to the value file:
root@raspberrypi:/sys/class/gpio/gpio25# echo 0 > value
So if writing to a file is how you control components that are outputs, how do you check the status of components that are inputs? If you guessed “reading a file,” then you’re absolutely right. Let’s try that now.
Simple pushbutton switches like the one in Figure 6-6 are great for controlling basic digital input. Best of all, they’re made to fit perfectly into a breadboard.
When you read a digital input on a Raspberry Pi, you’re checking to see if the pin is connected to either 3.3 volts or to ground. It’s important to remember that it must be either one or the other, and if you try to read a pin that’s not connected to either 3.3 volts or ground, you’ll get unexpected results. Once you understand how digital input with a pushbutton works, you can start using components like magnetic security switches, arcade joysticks, or even vending machine coin slots. Start by wiring up a switch to read its state:
Insert the pushbutton into the breadboard so that its leads straddle the middle channel.
Using a jumper wire, connect pin 24 from the Raspberry Pi to one of the top terminals of the button.
Connect the 3V3 pin from the Raspberry Pi to the positive power bus on the breadboard.
Connect one of the bottom terminals of the button to the power bus. Now when you push down on the button, the 3.3 volts will be connected to pin 24.
Remember what we said about how a digital input must be connected to either 3.3 volts or ground? When you let go of the button, pin 24 isn’t connected to either of those and is therefore floating. This condition will cause unexpected results, so let’s fix that. Use a 10K resistor (labeled with the colored bands: brown, black, orange, and then silver or gold) to connect the input side of the switch to the ground rail, which you connected to the Raspberry Pi’s ground in the output example. When the switch is not pressed, the pin will be connected to ground.
Electricity always follows the path of least resistance toward ground, so when you press the switch, the 3.3 volts will go toward the Raspberry Pi’s input pin, which has less resistance than the 10K resistor. When everything’s hooked up, it should look like Figure 6-7.
Now that the circuit is built, let’s read the value of the pin from the command line. If you’re not already running commands as root, type sudo su
.
As with the previous example, you need to export the input pin to userspace:
# echo 24 > /sys/class/gpio/export
Let’s change to the directory that was created during the export operation:
# cd /sys/class/gpio/gpio24
Now set the direction of the pin to input:
# echo in > direction
To read the value of the of the pin, you’ll use the cat
command, which will print the contents of files to the terminal. The command cat
gets its name because it can also be used to concatenate, or join, files. It can also display the contents of a file for you:
# cat value
0
The zero indicates that the pin is connected to ground. Now press and hold the button while you execute the command again:
# cat value
1
If you see the number 1, you’ll know you’ve got it right!
Now that you can use the Linux command line to control an LED or read the status of a button, let’s use a few of Linux’s built-in tools to create a very simple project that uses digital input and output.
Let’s say you’re leaving for a long vacation early tomorrow morning and you want to ward off would-be burglars from your home. A lamp timer is a good deterrent, but hardware stores are closed for the night and you won’t have time to get one before your flight in the morning. However, because you’re a Raspberry Pi hobbyist, you have a few supplies lying around, namely:
Raspberry Pi board
Breadboard
Jumper wires, female-to-male
PowerSwitch Tail II relay
Hookup wire
With these supplies, you can make your own programmable lamp timer using two powerful Linux tools: shell scripts and cron.
A shell script is a file that contains a series of commands (just like the ones you’ve been using to control and read the pins). Take a look at the following shell script and the explanation of the key lines:
#!/bin/bash echo Exporting pin $1. echo $1 > /sys/class/gpio/export echo Setting direction to out. echo out > /sys/class/gpio/gpio$1/direction echo Setting pin high. echo 1 > /sys/class/gpio/gpio$1/value
This line is required for all shell scripts.
$1
refers to the first command-line argument.
Instead of exporting a specific pin number, the script uses the first command-line argument.
Notice that the first command-line argument replaces the pin number here as well.
Save that as a text file called on.sh and make it executable with the chmod
command:
root@raspberrypi:/home/pi# chmod +x on.sh
sudo su
if you’re getting errors like “Permission denied.”A command-line argument is a way of passing information into a program or script by typing it in after name of the command. When you’re writing a shell script, $1
refers to the first command-line argument, $2
refers to the second, and so on. In the case of on.sh
, you’ll type in the pin number that you want to export and turn on. Instead of hard coding pin 25 into the shell script, it’s more universal by referring to the pin that was typed in at the command line. To export pin 25 and turn it on, you can now type:
root@raspberrypi:/home/pi/# ./on.sh 25
Exporting pin 25.
Setting direction to out.
Setting pin high.
If you still have the LED connected to pin 25 from earlier in the chapter, it should turn on. Let’s make another shell script called off.sh, which will turn the LED off. It will look like this:
#!/bin/bash echo Setting pin low. echo 0 > /sys/class/gpio/gpio$1/value echo Unexporting pin $1 echo $1 > /sys/class/gpio/unexport
Now let’s make it executable and run the script:
root@raspberrypi:/home/pi/temp#chmod +x off.sh
root@raspberrypi:/home/pi/temp#./off.sh 25
Setting pin low. Unexporting pin 25
If everything worked, the LED should have turned off.
Of course, a tiny little LED isn’t going to give off enough light to fool burglars into thinking that you’re home, so let’s hook up a lamp to the Raspberry Pi:
Remove the LED connected to pin 25.
Connect two strands of hookup wire to the breadboard, one that connects to pin 25 of the Raspberry Pi and the other to the ground bus.
The strand of wire that connects to pin 25 should be connected to the “+in” terminal of the PowerSwitch Tail.
The strand of wire that connects to ground should be connected to the “-in” terminal of the PowerSwitch Tail. Compare your circuit to Figure 6-8.
Plug the PowerSwitch Tail into the wall and plug a lamp into the PowerSwitch Tail. Be sure the lamp’s switch is in the on position.
Now when you execute ./on.sh 25
, the lamp should turn on; and if you execute ./off.sh 25
, the lamp should turn off!
So now you’ve packaged up a few different commands into two simple commands that can turn a pin on or off. And with the lamp connected to the Raspberry Pi through the PowerSwitch Tail, you can turn the lamp on or off with a single command. Now you can use cron
to schedule the light to turn on and off at different times of day. cron
is Linux’s job scheduler. With it, you can set commands to execute on specific times and dates, or you can have jobs run on a particular period (for example, once an hour). You’re going to schedule two jobs: one of them will turn the light on at 8:00 p.m., and the other will turn the light off at 2:00 a.m.
As with other time-dependent programs, you’ll want to make sure you’ve got the correct date and time set up on your Raspberry Pi, as described in “Setting the Date and Time”.
To add these jobs, you’ll have to edit the cron
table (a list of commands that Linux executes at specified times):
root@raspberrypi:/home/pi/# crontab -e
This will launch a text editor to change root’s cron
table (to change to the root user, type sudo su
). At the top of the file, you’ll see some information about how to modify the cron
table. Use your arrow keys to get to the bottom of the file and add these two entries at the end of the file:
0 20 * * * /home/pi/on.sh 25 0 2 * * * /home/pi/off.sh 25
cron
will ignore any lines that start with the hash mark. If you want to temporarily disable a line without deleting it or add a comment to the file, put a hash mark in front of the line.Press Ctrl-X to exit, press y to save the file when it prompts you, and hit Enter to accept the default filename. When the file is saved and you’re back at the command line, it should say installing new crontab
to indicate that the changes you’ve made are going to be executed by cron
.
cron
will let you schedule jobs for specific dates and times or at intervals. There are five time fields (or six if you want to schedule by year), each separated by a space followed by another space, then the command to execute; asterisks indicate that the job should execute each period (Table 6-1).
0 | 20 | * | * | * | /home/pi/on.sh 25 |
---|---|---|---|---|---|
Minute (:00) |
Hour (8 p.m.) |
Every day |
Every month |
Every day of the week |
Path to command |
Let’s say you only wanted the lamp to turn on every weekday. Table 6-2 shows what the crontab
entry would look like.
0 | 20 | * | * | 1-5 | /home/pi/on.sh 25 |
---|---|---|---|---|---|
Minute (:00) |
Hour (8 p.m.) |
Every day |
Every month |
Monday to Friday |
Path to command |
As another example, let’s say you have a shell script that checks if you have new mail and emails you if you do. Table 6-3 shows how you’d get that script to run every five minutes.
*/5 | * | * | * | * | /home/pi/checkMail.sh |
---|---|---|---|---|---|
Every five minutes |
Every hour |
Every day |
Every month |
Every day of the week |
Path to command |
The */5 indicates a period of every five minutes.
As you can see, cron
is a powerful tool that’s at your disposal for scheduling jobs for specific dates or times and at specific intervals.
This is the most comprehensive reference guide to the Raspberry Pi’s GPIO pins.
This command line utility makes it easier to work with GPIO pins from the command line. It’s bundled with the latest version of Raspbian. Try running the command gpio readall
to get an overview of all your pins.
If you don’t have enough pins to work with, Adafruit offers this guide to using the MCP23008 chip for 8 extra GPIO pins and the MCP23017 for 16 extra GPIO pins.