How To Use GPIO Pins On Raspberry Pi – Buttons And LED Tutorial

by Oscar

What Are The GPIO Pins on Raspberry Pi?

A great feature on the Raspberry Pi is the GPIO pins (stands for General Purpose Input Output). These GPIO pins on Raspberry Pi can be found in 2×13 header pins which can perform tasks include SPI, I2C, serial UART, 3V3 and 5V power.

Some of the links on this page are affiliate links. I receive a commission (at no extra cost to you) if you make a purchase after clicking on one of these affiliate links. This helps support the free content for the community on this website. Please read our Affiliate Link Policy for more information.

GPIO Pins On Raspberry Pi

There are eight of these pins can be used directly for digital output and input (Hight and Low). These pins can be set high by connecting it to a voltage supply, or set low by connecting it to ground.

So you can control electronics devices such as LEDs, Motor Driver and so on using these GPIO pins. Input devices like push buttons and toggle switches can also be used to control the Raspberry Pi.

GPIOs

How To Control and Use GPIO Pins on Raspberry Pi?

This includes two steps, software on the Pi, and how to connect the hardware.

Install RPi.GPIO Python Library

The RPi.GPIO Python Library probably have come pre-installed on your Raspbian OS, to verify this, fire up Python:

sudo python

and type in this line

import RPi.GPIO as GPIO

If you don’t get any error, you are should be fine. If you do get an error, then do the following to install the library.

To install it launch a command line (i.e. LXTerminal) and enter the following commands :

  1. Download the RPi GPIO Library
    wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.3.1a.tar.gz
  2. Extract the files
    tar zxf RPi.GPIO-0.3.1a.tar.gz
  3. Browse to the extracted folder
    cd RPi.GPIO-0.3.1a
  4. Install the library
     sudo python setup.py install

The Library should be ready now.

Usage of the Python RPi.GPIO  Library

[sourcecode language=”python”]

# import library

import RPi.GPIO as GPIO

# to use Raspberry Pi board pin numbers

GPIO.setmode(GPIO.BOARD) # or GPIO.setmode(GPIO.BCM)

# set up the GPIO Pins – for input or output

GPIO.setup(11, GPIO.IN)

GPIO.setup(13, GPIO.OUT)

# taking input value from Pin 11
input_value = GPIO.input(11)

# setting output value to Pin 13
GPIO.output(13, GPIO.HIGH)

#GPIO.output(13, GPIO.LOW)

[/sourcecode]

The difference between GPIO.setmode(GPIO.BOARD) and GPIO.setmode(GPIO.BCM) is the pin numbering system. BOARD signifies using the physical pin numbers on the Raspberry Pi P1 connector. BCM signifies the Broadcom SOC channel designation. However you should know the BCM channels changed a little between revision 1 and revision 2 of the Raspberry Pi board, and the BOARD numbering system stays working between board revisions.

A Simple LEDs and Push Button Test with Raspberry Pi GPIO

Connection of GPIO Pins On Raspberry Pi and LEDs/buttons

There are 8 available GPIO Pins on Raspberry Pi.

raspberry pi gpio pins

See connection shown in the diagram.

GPIO Pins On Raspberry Pi circuit connection

Resistors value can be caculated as this. My 5mm LED’s forward current is around 20mA (might be different to yours), voltage supply from RPi is 3.3V, so the resistor for LED is 3.3 V / 20 mA = 165 omh. For the push buttons, I used 1K ohm resistors.

IMAG0721

Source Code

[sourcecode language=”python”]
from time import sleep
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

GPIO.setup(16, GPIO.IN)
GPIO.setup(18, GPIO.IN)

GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)

# state – decides what LED should be on and off
state = 0

# increment – the direction of states
inc = 1

while True:

# state toggle button is pressed
if ( GPIO.input(16) == True ):

if (inc == 1):
state = state + 1;
else:
state = state – 1;

# reached the max state, time to go back (decrement)
if (state == 3):
inc = 0
# reached the min state, go back up (increment)
elif (state == 0):
inc = 1

if (state == 1):
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)
elif (state == 2):
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
GPIO.output(15, GPIO.LOW)
elif (state == 3):
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
GPIO.output(15, GPIO.HIGH)
else:
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)
print(“pressed B1 “, state)

# reset button is pressed
if ( GPIO.input(18) == True ):

state = 0
inc = 1
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)

print(“pressed B2 “, state)

sleep(0.2);
[/sourcecode]

Conclusion

Although the Raspberry Pi has much more powerful computational capacity than the Arduino, it’s shortage in digital pins and analogue pins is still a disadvantage for many DIY, electronics hobbyists. However there are possibilities in expanding the number of digital pins and adding analogue pins. I might do some projects around these area in the near future.

Leave a Comment

By using this form, you agree with the storage and handling of your data by this website. Note that all comments are held for moderation before appearing.

17 comments

Wayne Andersen 12th November 2019 - 9:44 pm

Is this the Oscar Liang that used to work at First Data about 15 years ago?

If so, this is the Wayne Andersen that used to work there also. I hope you are doing well and I’d like to hear what you are up to these days.

Well, if not, I’m still the Wayne Andersen that worked at First Data about 15 years ago.

Wayne

Reply
Oscar 18th November 2019 - 6:30 pm

Sorry to disappoint, but it’s the wrong Oscar :)

Reply
Brian 13th November 2014 - 10:13 pm

……used directly for digital output and input (Hight and Low).

……used directly for digital output and input (Hi and Low).

Reply
Andrew 17th July 2014 - 7:26 pm

I am having an issue where when I run the program it constantly says button 1 has been pressed and my lights stay on even after I close the program until I power down my raspberry pi (note: I am only using 2 LED’s)

Reply
Jeremy 25th September 2013 - 3:07 pm

Sorry i did add the indents in the code i pasted but the blog seems to have removed them.

Reply
Carmen 12th June 2014 - 10:49 pm

Hi, yeah this piece of writing is truly good and
I have learned lot of things from it regarding blogging. thanks.

Reply
Jeremy 25th September 2013 - 3:05 pm

Hi

I have followed your example but i get the following error:

ledpy.py”, line 39
if (inc == 1):
^
My code looks like this.

while True:

# state toggle button is pressed
if ( GPIO.input(7) == True ):

if (inc == 1):
state = state + 1;
else:
state = state – 1;

Please help !

Reply
knipskopp 19th September 2013 - 12:11 pm

i did a stupid mistake.
See Picture 2?
The Breadboard is seperated … Ground + 3.3v don’t go to the left side …..
once i plugged button 4 (and 5 ) on the right side, everything worked :)

Reply
Oscar 19th September 2013 - 5:32 pm

Aha! :-)

Reply
knipskopp 19th September 2013 - 9:05 am

Made a Photo with 3 Buttons : (working)
http://www.img-host.de/bild.php/42531,4buttons5LFI4.png

And a Photo with 4 Buttons: ( Button 4 flickers)
http://imgur.com/TavVZUt

sorry for 3 Comments. :(

Reply
Oscar 19th September 2013 - 10:12 am

oh.. once you mention “flickers” here… it hits me…

It might be the sampling frequency is too high for the buttons ( which is normal), you might also need add more logic to check if the button has been released and pressed again, and not pressed all the time (just ignore it if that’s the case), otherwise the button is not going to work very well.

Reply
knipskopp 19th September 2013 - 8:33 am

I also tried Pin 11 ( GPIO 17) instead of PIN 22 GPIO25. Same… Oo

above one line is missing: state = 0
Sorry, Copy+Paste Error :)

Reply
knipskopp 19th September 2013 - 7:58 am

Yes, it’s PI Rev 2 B with LAN + USB.
Prev, Next + Toggle work, if i attach another button, it flickers.

Code:
from time import sleep
import subprocess
import RPi.GPIO as GPIO
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)

GPIO.setup(16, GPIO.IN)
GPIO.setup(15, GPIO.IN)
GPIO.setup(18, GPIO.IN)
GPIO.setup(22, GPIO.IN)
def next():
p = subprocess.Popen([“mpc”, “next”], stdout=subprocess.PIPE)
output, err = p.communicate()
print “*** Running mpc next command ***n” # , output

def prev():
p = subprocess.Popen([“mpc”, “prev”], stdout=subprocess.PIPE)
output, err = p.communicate()
print “*** Running mpc prev command ***n”# , output

def toggle():
p = subprocess.Popen([“mpc”, “toggle”], stdout=subprocess.PIPE)
output, err = p.communicate()
print “*** Running mpc toggle command ***n”, output

def mpc(doit):
p = subprocess.Popen([“mpc”, doit], stdout=subprocess.PIPE)
output, err = p.communicate()
print “*** Running mpc toggle command ***n”, output

while True:

# next button is pressed
if ( GPIO.input(15) == True ):
print(“pressed GPIO 22 Pin 15 B3”, state)
next()
mpc(“current”)

# prev toggle button is pressed
if ( GPIO.input(16) == True ):
print(“pressed GPIO 23 Pin 16 B1”, state)
prev()
mpc(“current”)

# toggle button is pressed
if ( GPIO.input(18) == True ):
print(“pressed GPIO 24 PIN 18 B2 “, state)
toggle()

# button4 is pressed
if ( GPIO.input(22) == True ):
print(“pressed GPIO 25 PIN 22 B4 “, state)

sleep(0.2);

Reply
Oscar 19th September 2013 - 10:02 am

okay… the code looks okay to me (although I haven’t tested it on my RPi).

I would suggest debug the buttons first, and remove all the sub-routines. You can do this but having 4 button states variables (state1 – state4).

1. initialize all states to false .
2. when button pressed, check corresponding button state boolean value, if it’s false, now set it to true. Or vice verse.

Try this first :-)

Reply
knipskopp 18th September 2013 - 4:18 pm

Hi,
i extended your button layout, adding gpio 17 as input and dropped all led wireing.
3 button work like a charm.
however, if i try adding a fourth button via gpio25 it randomly flickers to high, without pressing a button.
any suggestions appreciated.
k.

Reply
Oscar 18th September 2013 - 5:02 pm

is your RPI rev 1 or 2?
the Pin layout diagram on in this post is Rev2, make sure the pin are correctly initialized as Input or output. (in our case, should all be inputs) NOTE: pin numbers are different from GPIO numbers!

if that doesn’t help , please post your code here so we can check it..

Reply
Ryat 5th September 2013 - 10:28 pm

Great read =D

Reply