Simple Use Of GPIO Example Using Python


Overview

This articles shows you the basic GPIO on the Raspberry-Pi using the prototype area of the Slice of Pi. This covers basic details on the GPIO pins, using Python library to allow access to the GPIO. There is an example circuit to build on the Slice and some code to get the outputs working.

This was originally a blog post on Matts blog at lwk.mjhosting.co.uk

 

GPIO Basic’s

R-Pi-300x225

The R-Pi has 17 GPIO pins brought out onto the header, most have alternated functions other than just I/O, there are two pins for UART, two for I2C and six for SPI. All the pins can be use for GPIO with either INPUT or OUTPUT, there also internal pull-up & pull-downs for each pin but the I2C pins have and onboard pull-up so using them for GPIO may not work in some cases.

Using any of the pins will require extra care, than most Arduino users maybe be used to. These pins are 3V3 not 5V like the AVR chips, and they a directly connected to the Broadcom chip at the heart of the R-Pi. This means there is not protection, if you send 5V down a pin there is a good chance of killing the Pi.

There will also be an issue with trying to draw to much power form the pins, according to the data-sheet each pin programmed to current drive between 2mA and 16mA, and it has been warned that trying to draw 16mA from several pins at once could also lead to a damaged Pi.

Also from the wiki the “maximum permitted current draw from the 3v3 pin is 50mA” and the “maximum permitted current draw from the 5v pin is the USB input current (usually 1A) minus any current draw from the rest of the board.” The current draw for Model B is stated as 700mA so with a 1A power supply this leaves about 300mA to play with.

Anyway enough about power theres still plenty to try driving some basis LED’s and use the UART to talk to an XRF.

So how does one go about talking to the GPIO’s? Well thanks to a little python library its nice and simple. I’ll be using a Debian install but this should work on the others.

 

Installing RPi.GPIO

NOTE: The instructions here refer to an early version of RPi.GPIO. Please search the web for the latest version and replace the version numbers in the instructions below.

RPi.GPIO is a small python library that take some of the complexity out of driving the GPIO pins, once install a single LED can be lit with 3 lines of python. Installing the library is almost as simple, either at a text console or using LXTerminal enter the following

$ wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.1.0.tar.gz
$ tar zxf RPi.GPIO-0.1.0.tar.gz
$ cd RPi.GPIO-0.1.0
$ sudo python setup.py install

RPi.GPIO-setup

It should look something like the above just before you hit enter on the last command. That’s it we now have RPi.GPIO python library installed.

 

LED and Pushbutton Slice

So now I need and LED or two to Flash. So using a Slice of Pi from Ciseco I have wired up four LED’s with resistors and two Push button’s.

First to be soldered up were the LED’s and push buttons then I adde the resistors and connecting wires.

To keep the GPIO pins nice and safe I’m using 470R resistors for the RED,YELLOW and GREEN LED’s and a 330R for the BLUE, this will keep the current of each led to around 6-7mA. Here’s the schematic and the board

Slice-Schematic-11 IMG_7468-e1336337321668-225x300

If you look at the LED’s I’m using the 3.3v rail to power the led and have the cathode going to the GPIO’s this mean that to turn the LED on we set the output to LOW or False (in python’s case) but to turn the off we set the output to HIGH or True.
This means we a sinking the current through the Raspberry Pi rather that trying to source it from the pin’s. For the push button we are using a 10K pull-down resistor, this makes sure the button read a solid LOW or False when not pressed, when pressed the 3.3v is connected and we get a solid HIGH or True reading.

 

Some Code

I said turning LED’s on was easy well try this in a terminal:

$ sudo python
>>> import RPi.GPIO as GPIO
>>> GPIO.setup(18, GPIO.OUT)
>>> GPIO.output(18, False)

 

Again it should look a little some thing like this

GPIO-code

Red-LED

Anyone trying this themselves may notice that the RED LED actual turned on after the GPIO.setup line and that GPIO.output did nothing. This is because we have the cathode of the LED’s wired to the GPIO, and are using the Raspberry Pi to switch the GND. The default state for a output pin is LOW and so this also power to flow throughout the LED.  So how about turning that yellow LED on:-

>>> GPIO.setup(16, GPIO.OUT)

 

GPIO-Code-2

Yellow-LED

Simple, now to turn both LED’s off we set the inputs HIGH or True like so:

>>> GPIO.output(18, True)
>>> GPIO.output(16, True)

 

Now why if we wired the red LED to GPIO5 on the Slice of Pi, why am I using 18 to control it? Well theres a bit of fun with the pin numbering on Raspberry Pi, and some how i don’t expect it to go anyway and time soon, it like that odd gap on the Arduino headers. It comes from this post originally Pinout for GPIO connectors, better shown in the left pic bellow, anyway it turns out the original numbering of GPIO0-GPOI7 relates to nothing logical once inside linux, as they pins are accessed via there BCM2835(the chip on the Pi) GPIO numbers. See the right pic for the internal numbering, also all the signal named pins can be used as GPIO’s and have numbers as well.

Anyway RPi.GPIO python library has used yet another form of reference which is to us the pin number on the header, This give three names for each pin 🙁 When referred to by pin number (officially P1_18) we are talking about pin 18 as counted out on the header, GPIO5 by name and GPIO24 internally by the BCM2835. Now if you ever work with the IO using the Shell file access or C memory mapped registers your going to use the BCM2835 numbering.
Confused yet, I was till did a little table to help. There more on this on the Raspberry Pi wiki page Low Level Peripherals

For now I will leave you with the diagrams and table bellow, and just know you need to use the RPi.GPIO numbers in python.
This is all ready getting far to long so ill cover the inputs and making something interactive in another post.

GPIOs

Pin Numbers RPi.GPIO Raspberry Pi Name BCM2835
P1_01 1 3V3
P1_02 2 5V0
P1_03 3 SDA0 GPIO0
P1_04 4 DNC
P1_05 5 SCL0 GPIO1
P1_06 6 GND
P1_07 7 GPIO7 GPIO4
P1_08 8 TXD GPIO14
P1_09 9 DNC
P1_10 10 RXD GPIO15
P1_11 11 GPIO0 GPIO17
P1_12 12 GPIO1 GPIO18
P1_13 13 GPIO2 GPIO21
P1_14 14 DNC
P1_15 15 GPIO3 GPIO22
P1_16 16 GPIO4 GPIO23
P1_17 17 DNC
P1_18 18 GPIO5 GPIO24
P1_19 19 SPI_MOSI GPIO10
P1_20 20 DNC
P1_21 21 SPI_MISO GPIO9
P1_22 22 GPIO6 GPIO25
P1_23 23 SPI_SCLK GPIO11
P1_24 24 SPI_CE0_N GPIO8
P1_25 25 DNC
P1_26 26 SPI_CE1_N GPIO7

 

Blink on the Pi

In Below section, I’m going to show a quick Blinky example, for now I’m going to stick with just using python in interactive mode form the terminal, but we may get into script files after I show the basic’s of inputs.

Straight in with the the code then:

$ sudo python
>>> from time import sleep
>>> import RPi.GPIO as GPIO
>>> GPIO.setup(18, GPIO.OUT)
>>> while 1:
...     GPIO.output(18, False)
...     sleep(1)
...     GPIO.output(18, True)
...     sleep(1)
...

GPIO-Code-3

So a little more to that than before, notice the prompt changed after the

while 1:

to

...

After this we need to indent the code with a tab for it to be considered part of the loop. Hit enter twice after the

sleep(1)

and we now have a blinking red LED 🙂

Now to stop the loop and get back to the python prompt use Ctrl-C and to get out of python and back to the bash prompt you can use Ctrl-D. Below you can see I just used Ctrl-C to get back to the python prompt
GPIO-Code-4

 

3 Inputs

Time to play with the push buttons, here the code again, if you are at the python prompt from above then just ignore the first two lines:

 $ sudo python
>>> import RPi.GPIO as GPIO
>>> GPIO.setup(11, GPIO.IN)
>>> GPIO.input(11)

Now we should get back a

False

as below
GPIO-Code-5

Try holding down the button and doing that last line again

>>> GPIO.input(11)

 

This time you should get back

True

Now lets see if we can’t combine inputs and outputs

 

4 Combining Inputs and Outputs

Ill give the full code example again:

$ sudo pyton
>>> import RPi.GPIO as GPIO
>>> GPIO.setup(18, GPIO.OUT)
>>> GPIO.setup(11, GPIO.IN)
>>> while 1:
...     if GPIO.input(11):
...         GPIO.output(18, False)
...     else:
...         GPIO.output(18, True)
...

GPIO-Code-6
Now have a simple push button turning on an LED

 

5 Something a little more complex

So it’s time to move onto something a little more complex and for this I’m going to start using a IDE called Geany, its already available on the Pi’s and has been used in some great youtube videos by Liam, check out his channel RaspberryPiTutorials

There are however a few limits to using geany, first we need to install xterm (at least on the debian image)

$ sudo apt-get install xterm

 

The second is a little more tricky, using RPi.GPIO needs root permission, hence we have been using sudo python up till now, luckily we can ask geany todo the same. Open geany form the Programming menu, once it loads, we want a new file from the main.py template, try the little down arrow at the side of the ‘New’ button.
This should give us an untitled.py file pre filled with a load of text, we will go back to that in a bit. Next click on the ‘Build’ menu and then ‘Set Build Commands’. In the ‘Execute’ box near the bottom add the word “sudo” in front of the ‘python “%f” and hit ‘OK’

Geany_1

Now back to that file in the editor, lets delete everything but the first line #!/usr/bin/env python and type in some code, lets try out our button to led example from above:

Geany_2

Now hit the ‘Execute’ button (3 little gears) and a black window pops up in which the python script will run and we have our push button LED again. But I wired up 4 LED’s and two Buttons so lets get them all working together:

#!/usr/bin/env python
from time import sleep
# get the GPIO Library
import RPi.GPIO as GPIO

# setup some names references to the LED's and buttons
# red     = pin 18
# yellow  = pin 16
# green   = pin 15
# blue    = pin 13

# using an list to hold the led numbers
leds = [13, 15, 16, 18]
# the input buttons
up = 12
down = 11

# setup the pins as output and input as needed
# looping over the list 
for n in leds:
    GPIO.setup(n, GPIO.OUT)

GPIO.setup(up, GPIO.IN)
GPIO.setup(down, GPIO.IN)
# turn off all but the blue LED
GPIO.output(leds[3], True)
GPIO.output(leds[2], True)
GPIO.output(leds[1], True)
GPIO.output(leds[0], False)

#state trackers
level = 0
oldlevel = level

while 1:
    if GPIO.input(up):
        #up button pressed
        if level < 3:
            level += 1
    elif GPIO.input(down):
        #down button pressed
        if level > 0:
            level -= 1
    if oldlevel != level:
        # turn off last led and turn on next one
        GPIO.output(leds[oldlevel], True)
        GPIO.output(leds[level], False)
        # update state tracker
        oldlevel = level
        # sleep for a bit so button press is counted only once
        sleep(1)

 

Try it out, file is here, if all goes well the blue LED will light up and clicking the up button will change it to the green, and so on.

XRF_URF

Another long post but should give an idea of how easy it can be to use the GPIO’s on the Raspberry Pi with a little Python.
Next I’ll be looking at either the little Charlieplex LED display I built on another slice or it will be about using the XRF and URF radio modules with pyserial. Here’s some pics 😉

 

Original Post: http://openmicros.org/index.php/articles/94-ciseco-product-documentation/raspberry-pi/217-getting-started-with-raspberry-pi-gpio-and-python

Share Button

Leave a Reply