Instructables
Picture of Raspberry Pi: Python scripting the GPIO
The GPIO: General Purpose Input/Output lets you interface your Raspberry Pi with the outside world, making it a powerful interactive device for just $40-$50.

This Instructable will show you how to install the GPIO package on your Raspberry Pi and how to wire up a simple push button circuit with an LED.

I use the command-line and Python for this, no web browser or GUI.

Before you do this Instructable, make sure you have your Raspberry Pi ready for action. My Ultimate Raspberry Pi Configuration Guide covers how to do this in detail.

You will want to have an internet connection to download the packages and probably use ssh. 
 
Remove these adsRemove these ads by Signing Up

Step 1: Gather your components

Picture of Gather your components
Components
* Raspberry Pi
* Cobbler breakout board with cable — you can order this from Adafruit for $8.
* Breadboard
* Wires — breadboard or otherwise
* standard LED
* 270 Ohm resistor
* 1K resistor
* 10K resistor
* Push button
* USB power for RPI (not pictured)
* Monitor + keyboard (not pictured)

Tools
* wire-stripper
* small diagonal snips
* multimeter for checking continuity


Step 2: Assemble your circuit

Picture of Assemble your circuit
switch_led.jpg
We will have a simple push button that will turn an LED on when the button is pressed and off when it is released. I know, it's not super-exciting, but think of this as a building block for digital input and output.

Here is the schematic and breadboard diagram.

The LED is straightforward: 270 Ohm resistor is needed to light up the LED from a 3.3V input.

The concept is simple: the LED is an output of pin 4 and the button is an input of pin 22. The button circuit has a pull-down resistor. Pin 22 will be pulled down to zero through the 10K resistor when the button is inactive. When it gets pressed, the 3.3V power from the Raspberry Pi goes into the pin 22 input, bypassing the 10K resistor.

Without the 10K resistor, you'll have a floating input and will get erratic behavior in your code. The 1K resistor protects the Raspberry Pi from too much current.
scottkildall (author) 5 months ago

Good point. I'm usually stopping my Python scripts with a ctrl-C rather than an event like a keydown, and so the GPIO.cleanup() doesn't get called. My workaround is setting the warnings to false. But, as you point out, the GPIOs will stay at the state they were last in, leaving the LEDs on — better coding practice would be to properly close the ports.

cudy7895 months ago
sometimes if your don't properly close the gpios they stay at the state they were last set. when I was making a robot with my pi, and I quickly cancelled the script so it wouldn't run into something, it continued on its merry way. simply put GPIO.cleanup() at the end of your program, and you should stop getting that warning. great little indestructible though:)
cudy789 cudy7895 months ago
great little instructable*