Raspberry GPIo
Raspberry GPIo
com tutorial
Available online at: http://sfe.io/t424
Contents
Introduction
GPIO Pinout
Hardware Setup
Python (RPi.GPIO) API
Python (RPi.GPIO) Example
C (WiringPi) Setup
C (WiringPi) API
C (WiringPi) Example
Using an IDE!
Resources & Going Further
Introduction
Relative to its size the Raspberry Pi is a powerhorse of a computer it can drive HDMI displays, process mouse, keyboard,
and camera inputs, connect to the Internet, and run full-featured Linux distributions. But its more than just a small
computer, its a hardware prototyping tool! The Pi hasbi-directional I/O pins, which you can use to drive LEDs, spin
motors, or read button presses.
This tutorial applies to the Raspberry Pi Model B, the Raspberry Pi Model B+ and the new Raspberry Pi 2 Model B.
Suggested Reading
This tutorial will assume you have Raspbian installed on your Raspberry Pi. Raspbian is the most popular, well-supported
Linux distribution available for the Pi. If you dont have Raspbian set up, check out ourSetting Up Raspbian tutorial before
continuing down this rabbit hole.
Other, more general purpose tutorials you might be interested in reading include:
Pulse-Width Modulation You can use PWM to dim LEDs or send signals to servo motors. The RPi has a single
PWM-capable pin.
Light-Emitting Diodes (LEDs) To test the output capabilities of the Pi, well be driving a lot of LEDs.
Switch Basics And to test inputs to the Pi, well be using buttons and switches.
Pull-Up Resistors The Pi has internal pull-up (and pull-down) resistors. These are very handy when youre interfacing
buttons with the little computer.
Suggested Viewing
Check out our Raspberry Pi video tutorials if you want a more visual introduction to the Pi!
Getting Started With The Raspberry Pi
Part 1
Part 2
Part 3
GPIO Pinout
The Raspberry Pi offers up its GPIO over a standard male header on the board. Over the years the header has expanded
from 26 pins to 40 pins while maintaining the original pinout.
There are (at least) two, different numbering schemes you may encounter when referencing Pi pin numbers: (1) Broadcom
chip-specific pin numbers and (2) P1 physical pin numbers. Youre usually free to use either number-system, but many
programs require that you declare which scheme youre using at the very beginning of your program.
Heres a table showing all 26 pins on the P1 header, including any special function they may have, and their dual numbers:
Python (BCM)
WiringPi GPIO
Name
P1 Pin Numb
3.3v DC Power
SDA
SCL
GPIO04 (GPIO_GCLK)
Ground
G4
G17
17
GPIO17 (GPIO_GEN0)
11
G27
27
GPIO27 (GPIO_GEN2)
13
G22
22
GPIO22 (GPIO_GEN3)
15
3.3v DC Power
17 18 GPIO24 (GPIO_GEN5)
5 24 G24
MOSI
12
GPIO10 (SPI_MOSI)
19 20
MISO
13
GPIO09 (SPI_MISO)
21 22 GPIO25 (GPIO_GEN6)
GPIO11 (SPI_CLK)
23 24
GPIO08 (SPI_CE0_N)
10
CD0
Ground
25 26
GPIO07 (SPI_CE1_N)
11
CE1
IDSC
IDSD
30
Ground
6 25 G25
G05
21
GPIO05
29 30
Ground
G6
22
GPIO06
31 32
GPIO12
G13 13
23
GPIO13
33 34
Ground
G19 19
24
GPIO19
35 36
GPIO16
27 16 G16
G26 26
25
GPIO26
37 38
GPIO20
28 20 G20
Ground
39 40
GPIO21
29 21 G21
26 12 G12
This table shows the Pi pin header numbers, element14 given names, wiringPi numbers, Python numbers, and related
silkscreen on the wedge.
Note: The Broadcom pin numbers above relate to Pi Model 2 and later only. If you have an older Rev1 Pi, check out this
link for your Broadcom pin numbers.
As you can see, the Pi not only gives you access to the bi-directional I/O pins, but also Serial (UART), I2C, SPI, and even
some PWM (analog output).
Hardware Setup
To get a head start you can assemble the circuit now. Well use this setup for both the C and Python examples. Well use two
LEDs to test the output functionality (digital and PWM), and a button to test the input.
connections to original pi
If you dont have a Pi Wedge,male-to-female jumper wires help to make an easy transition from Pi to breadboard.
Setup Stuff
In order to us RPi.GPIO throughout the rest of your Python script, you need to put this statement at the top of your file:
language:Python
import RPi.GPIO as GPIO
That statement includes the RPi.GPIO module, and goes a step further by providing a local nameGPIO
Outputs
Digital Output
To write a pin high or low, use the GPIO.output([pin], [GPIO.LOW, GPIO.HIGH]) function. For example, if
you want to set pin 18 high, write:
language:Python
GPIO.output(18, GPIO.HIGH)
Writing a pin to GPIO.HIGH will drive it to 3.3V, and GPIO.LOW will set it to 0V. For the lazy, alternative to
GPIO.HIGH and GPIO.LOW, you can use either 1, True, 0 or False to set a pin value.
Inputs
If a pin is configured as an input, you can use the GPIO.input([pin]) function to read its value. The input()
function will return either a True or False indicating whether the pin is HIGH or LOW. You can use an if statement to
test this, for example
language:Python
if GPIO.input(17):
print("Pin 11 is HIGH")
else:
print("Pin 11 is LOW")
will read pin 17 and print whether its being read as HIGH or LOW.
Pull-Up/Down Resistors
Remember back to the GPIO.setup() function where we declared whether a pin was an input or output? Theres an
optional third parameter to that function, which you can use to set pull-up or pull-down resistors. To use a pull-up resistor
on a pin, add pull_up_down=GPIO.PUD_UP as a third parameter in GPIO.setup. Or, if you need a pull-down
resistor, instead use pull_up_down=GPIO.PUD_DOWN.
For example, to use a pull-up resistor on GPIO 17, write this into your setup:
language:Python
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
Etc.
Delays
If you need to slow your Python script down, you can add delays. To incorporate delays into your script, youll need to
include another module: time. This line, at the top of your script, will do it for you:
language:Python
include time
Then, throughout the rest of your script, you can use time.sleep([seconds]) to give your script a rest. You can use
decimals to precisely set your delay. For example, to delay 250 milliseconds, write:
language:Python
time.sleep(0.25)
The time module includes all sorts of useful functions, on top of sleep. Check out the reference here.
Garbage Collecting
Once your script has run its course, be kind to the next process that might use your GPIOs by cleaning up after yourself.
Use the GPIO.cleanup() command at the end of your script to release any resources your script may be using.
Your Pi will survive if you forget to add this command, but it is good practice to include wherever you can.
Now then. Lets incorporate everything we learned here into an example script to try everything out.
1. Create a File
To begin, we need to create a Python file. You can do this through the GUI-based file explorer. Or, if you want a terminalbased solution, open up LXTerminal, and navigate to a folder youd like the file to live (or create one). And create a new
folder with these commands:
pi@raspberrypi ~/code $ mkdir python
pi@raspberrypi ~/code $ cd python
.py aextension. Then open it up in your favorite text editor. Nano
Create a file well call ours blinker and terminate it with
works, as does Pis default GUI text editor, Leafpad.
pi@raspberrypi ~/code/python $ touch blinker.py
pi@raspberrypi ~/code/python $ leafpad blinker.py &
Thatll open up a blank text file (the & will open it in the background, leaving the terminal in place for future use). Time for
some code!
2. Codify
Heres an example sketch that incorporates everything we learned on the last page. It does a little input and output, and even
handles some PWM. This assumes youve set up the circuit as arranged on theHardware Setup page.
language:Python
# External module imports
import RPi.GPIO as GPIO
import time
# Pin Definitons:
pwmPin = 18 # Broadcom pin 18 (P1 pin 12)
ledPin = 23 # Broadcom pin 23 (P1 pin 16)
butPin = 17 # Broadcom pin 17 (P1 pin 11)
dc = 95 # duty cycle (0-100) for PWM pin
# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(ledPin, GPIO.OUT) # LED pin set as output
GPIO.setup(pwmPin, GPIO.OUT) # PWM pin set as output
pwm = GPIO.PWM(pwmPin, 50) # Initialize PWM on pwmPin 100Hz frequency
GPIO.setup(butPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pu
# Initial state for LEDs:
GPIO.output(ledPin, GPIO.LOW)
pwm.start(dc)
print("Here we go! Press CTRL+C to exit")
try:
while 1:
if GPIO.input(butPin): # button is released
pwm.ChangeDutyCycle(dc)
GPIO.output(ledPin, GPIO.LOW)
else: # button is pressed:
pwm.ChangeDutyCycle(100-dc)
GPIO.output(ledPin, GPIO.HIGH)
time.sleep(0.075)
GPIO.output(ledPin, GPIO.LOW)
time.sleep(0.075)
except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:
pwm.stop() # stop PWM
GPIO.cleanup() # cleanup all GPIO
After youve typed all of that in (dont forget your whitespace!)save.
C (WiringPi) Setup
Python is a great GPIO-driving option, especially if youre used to it. But if youre a rickety old programmer, unfamiliar with
the whitespace-driven scripting language, and would rather live within the happy confines of C, then let me introduce the
WiringPi library.
1) Install Wiring Pi
WiringPi is not included with Raspbian, so, to begin, youll need to download and install it. That means your Pi will need a
connection to the Internet either via Ethernet orWiFi.
Once your Pi is Internet-enabled, visit the WiringPi homepage for instructions on downloading and installing the library.
We highly recommend using Git to download the latest version. As long as you have Git installed, these commands should
be all you need to download and install WiringPi:
pi@raspberrypi
pi@raspberrypi
pi@raspberrypi
pi@raspberrypi
pi@raspberrypi
2) Test Wiring Pi
WiringPi is awesome because its actually more than just a C library, it includes acommand-line utility as well! You can
test your installation of WiringPi with the gpio utility.
Open up a terminal, and try some of these system calls:
pi@raspberrypi ~/code $ gpio -g mode 18 output
pi@raspberrypi ~/code $ gpio -g write 18 1
pi@raspberrypi ~/code $ gpio -g write 18 0
As long as your LED is still connected to pin 18 it should blink on and off following the last two commands.
Or, to test the button, type:
pi@raspberrypi ~/code $ gpio -g mode 17 up
pi@raspberrypi ~/code $ gpio -g read 17
Either 0 or 1 will be returned, depending on whether the button is pressed or not. Try typing that last line again while
pressing the button.
The gpio utility, as stated in the manual, is a swiss army knife command-line tool. We highly recommend checking out the
man page (type man gpio) to discover everything it can do.
If youre ready to get on with some C-style programming, head over to the next page. Well overview some of the most
useful functions provided by the WiringPi library.
C (WiringPi) API
On this page well discuss some of the most useful functions provided by the WiringPi library. Its tailored to look a lot like
Arduino, so if youve done any Arduino programming some of this may look familiar.
Setup Stuff
To begin, youll need to include the library. At the beginning of your program, type:
language:c
#include <wiringPi.h>
After youve included the library, your first steps should be to initialize it. This step also determines whichpin numbering
scheme youll be using throughout the rest of your program. Pickone of these function calls to initialize the library:
language:c
wiringPiSetup(); // Initializes wiringPi using wiringPi's simlified number system.
wiringPiSetupGpio(); // Initializes wiringPi using the Broadcom GPIO pin numbers
WiringPis simplified number system introduces a third pin-numbering scheme. We didnt show it in the table earlier, if you
want to use this scheme, check out their pins page for an overview.
Keep in mind that the above example uses the Broadcom GPIO pin-numbering scheme.
Digital Output
The digitalWrite([pin], [HIGH/LOW]) function can be used to set an output pin either HIGH or LOW. Easy
enough, if youre an Arduino user.
To set pin 23 as HIGH, for example, simply call:
language:c
digitalWrite(23, HIGH);
PWM (Analog) Output
For the lone PWM pin, you can use pwmWrite([pin], [0-1023]) to set it to a value between 0 and 1024. As an
example
language:c
pwmWrite(18, 723);
will set pin 18 to a duty cycle around 70%.
Digital Input
If youre an Arduino veteran, you probably know what comes next. To read the digital state of a pin,
digitalRead([pin]) is your function. For example
language:c
if (digitalRead(17))
printf("Pin 17 is HIGH\n");
else
printf("Pin 17 is LOW\n");
digitalRead() function returns 1 if the pin is HIGH and 0 if its LOW.
will print the status of pin 22. The
Pull-Up/Down Resistors
Need some pull-up or pull-down resistors on your digital input? Use the pullUpDnControl([pin], [PUD_OFF,
PUD_DOWN, PUD_UP]) function to pull your pin.
For example, if you have a button on pin 22 and need some help pulling it up, write:
language:c
pullUpDnControl(17, PUD_UP);
That comes in handy if your button pulls low when its pressed.
Delays
Slowing down those blinking LEDs is always useful assuming you actually want to differentiate between on and off.
WiringPi includes two delay functions to choose from: delay([milliseconds]) and
delayMicroseconds([microseconds])
. The standard delay will halt the program flow for a specified number of milliseconds. If you want to delay for 2 seconds,
for example, write:
language:c
delay(2000);
Or you can use delayMicroseconds() to get a more precise, microsecond-level delay.
Now that you know the basics, lets apply them to an example piece of code.
C (WiringPi) Example
The intention of WiringPi is to make your I/O code look as Arduino-ified as possible. However keep in mind that were no
loop() or setup(), just int main(void).
longer existing in the comfy confines of Arduino theres no
Follow along here as we create an example C file, incorporate the WiringPi library, and compile and run that program.
Create blinker.c
Using the terminal, navigate to a folder of your choice and create a new file blinker.c. Then open that file in a text editor
(Nano or Leafpad are included with Raspbian).
pi@raspberrypi
pi@raspberrypi
pi@raspberrypi
pi@raspberrypi
The commands above will open your blinker.c file in Leafpad, while leaving your terminal functioning in-directory in th
background.
Program!
Heres an example program that includes a little bit of everything we talked about on the last page. Copy and paste, or write
it yourself to get some extra reinforcement.
language:c
#include <stdio.h>
// Used for printf() statements
#include <wiringPi.h> // Include WiringPi library!
// Pin number declarations. We're using the Broadcom chip pin numbers.
const int pwmPin = 18; // PWM LED - Broadcom pin 18, P1 pin 12
const int ledPin = 23; // Regular LED - Broadcom pin 23, P1 pin 16
const int butPin = 17; // Active-low button - Broadcom pin 17, P1 pin 11
const int pwmValue = 75; // Use this to set an LED brightness
int main(void)
{
// Setup stuff:
wiringPiSetupGpio(); // Initialize wiringPi -- using Broadcom pin numbers
pinMode(pwmPin, PWM_OUTPUT); // Set PWM LED as PWM output
pinMode(ledPin, OUTPUT);
// Set regular LED as output
pinMode(butPin, INPUT);
// Set button as INPUT
If typing all of that code in a bland, black-and-white, non-highlighting editor hurt your brain, check out the next page where
we introduce a simple IDE that makes your programming more efficient.
Using an IDE!
Thus far weve been using simple text-editors Leafpad or Nano to write our Python and C programs. So seasoned
programmers are probably missing a whole lot of features assumed of even the most basic editors: auto-tabbing, context-
highlighting, even automated building. If you want to incorporate any of those features, we recommend using an IDE
(integrated development environment). One of our favorite Pi IDEs isGeany, heres how to get it up and running.
Or, from the terminal, you can type sudo geany. You can even open a file in Geany, directly from the command line. To
open our previous C file, for example, type sudo geany blinker.c.
Using Geany
Once Geany is running, you can create a new file by going to File > New. Saving the file as either .c or .py (or any other
common language file extension) will immediately inform Geany what kind of language youre working with, so it can start
highlighting your text.
Geany can be used with most languages, including the Python and C examples weve just examined. Some tweaks to the
default IDE options are necessary, though. Heres an overview of using Geany with each language.
with C and WiringPi
Lets recreate ourWiringPi Example with Geany. Open the blinker.c created earlier within the confines of Geany. You
should immediately be presented with some very pleasant color-coding.
Before trying to compile the code, though, youll need to tweak some of the build options. Go up toBuild and Set Build
-l wiringPi.
Commands. Inside the Compile and Build text blocks, tack this on to the end of the default command:
That will load the wiringPi library.
No building required with Python! Once youre script is written, simply click the Execute gear up top. Again, running will
produce a separate terminal to pop up. To exit, simply press CTRL+C.
Geany has tons of features beyond what weve covered here. Check out the tabs at the bottom. Check out the menus up top.
Experiment and see how the IDE can make your programming life easier!
WiringPi Hompeage The home of WiringPi and a variety of other Raspberry-Pi-related tools. Check it out!
RPi.GPIO Homepage Home of the Raspberry Pi GPIO python module. Great source for API and documentation.
If youre looking for some project inspiration, here are some more SparkFun tutorials where youll be able to leverage your
newfound Pi programming skills:
Raspberry Pi Twitter Monitor How to use a Raspberry Pi to monitor Twitter for hashtags and blink an LED.
Getting Started with the BrickPi How to connect your Raspberry Pi to Lego Mindstorms, using the BrickPi.
pcDuino 2 Hookup Guide An introduction to the pcDuino an equally (if not more) powerful single board computer.