Tutorial: Raspberry Pi GPIO Programming Using Python [Full Guide]

Overview

In this tutorial, you will learn how to program Raspberry Pi GPIO using Python 3. Two most famous libraries, Gpiozero and Rpi.GPIO is explained.

What You Will Learn

  • Introduction to GPIO pins
  • Installing Gpiozero and Rpi.GPIO libraries
  • Controlling these components: LED, Button, Bargraph, Buzzer, RGB LED, LDR (Light sensor)
raspberry-pi-gpio-2

GPIO Pinout

General Purpose Input Output pins called GPIO are the 40 pins that you can use to connect other components to your board. The arrangement of the pins is as follows:

raspberry pi gpio pins
raspberry pi gpio pins 2

If you have installed Raspbian Desktop on your Raspberry Pi board, you can see  the pins number by entering the pinout command

raspberry pi gpio pins terminal

Each of these pins has certain features:

PWM (pulse-width modulation)

  • Software PWM available on all pins
  • Hardware PWM available on GPIO12, GPIO13, GPIO18, GPIO19

SPI

  • SPI0: MOSI (GPIO10); MISO (GPIO9); SCLK (GPIO11); CE0 (GPIO8), CE1 (GPIO7)
  • SPI1: MOSI (GPIO20); MISO (GPIO19); SCLK (GPIO21); CE0 (GPIO18); CE1 (GPIO17); CE2 (GPIO16)

I2C

  • Data: (GPIO2); Clock (GPIO3)
  • EEPROM Data: (GPIO0); EEPROM Clock (GPIO1)

Serial

  • TX (GPIO14); RX (GPIO15)

Python Gpiozero API

This library is one of the most comprehensive libraries available to control the Raspberry Pi input and output pins. Gpiozero is in Python language.

Many components have already been defined in this library. (such as an LED, Button, Bargraph LED, etc); Therefore working with this library is quite easy and you can simply control different components.

Note
this library has different classes for each component. Each class also has a variety of methods. You don’t need to know about object-oriented programming in this tutorial, but to better understand programming, we recommend you to learn object-oriented programming.

How to Setup Gpiozero?

This library is available on Raspbian operating system by default and you don’t need to install it.
if your OP is not Raspbian, you can install the library using the following commands:
Python 3: sudo pip3 install gpiozero
Pythone 2: sudo pip install gpiozero
To use this library, all you need to do is to import it in the Python programming environment.
Methode 1 (Recommended): from gpiozero import [name of class]
Methode 2: import gpiozero

Basic Commands

Now you can use the defined commands in the library.

LED-related commands:
Defining the pin connected to the LED: led = LED(# of pin)
Turning on: on()
Turning off: off()
Changing status*: toggle()
Blinking*: blink()
*Turning LED on if it’s off and vice-versa.

Button-related commands:
Defining the pin connected to the button: button = Button(# of a pin)
Wait until a button is pressed: wait_for_press ()
Wait until the button is released: wait_for_release ()
If the button is pressed returns 1 otherwise returns 0: is_pressed
Perform specific function when the button is pressed: when_pressed
Perform specific function when the button is released: when_released

Bargraph-related commands:

Defining the pin connected to Bargraph: graph = LEDBarGraph(# of pins)
Turning a number of LEDs on: graph.value = value
Buzzer-related commands:
Defining the pin connected to Buzzer: buzzer = Buzzer (# of a pin)
Turning on: on()
Turning off: off()
Changing status: toggle()

RGB LED commands:

Defining the pins connected to LED: led = RGBLED(red=#, green=#, blue=#)
Turning the red color on: led.red = value
Turning the green color on: led.green = value
Turning the blue color on: led.blue = value
Turning all colors on: on()
Turning all colors off: off()
Changing status: toggle()

LDR Commands:

Define the pin connected to photocell: sensor = LightSensor(# of a pin)
Waiting for the environment to light down then executes the next commands: wait_for_dark ()
Waiting for the environment to light up then executes the next commands: wait_for_light ()
If the environment is light, it returns True, otherwise returns False: light_detected 
Performing a specific function when the environment is dark: when_dark
Performing a specific function when the environment is light: when_light

For more information and extra commands, check this link.

Python RPi.GPIO API

Another common library in GPIO programming with python is RPi.GPIO. Let’s see how it is installed and its basic commands.

Setting Up RPi.GPIO

This library is also installed on Raspbian OS by default. To use this library, you need to import in the Python programming environment: import RPi.GPIO

Basic Commands

Using pins BCM numbers: GPIO.setmode(GPIO.BCM)
Defining the pin as input: GPIO.setup(# of pin, GPIO.IN)
Defining the pin as an output: GPIO.setup(# of pin, GPIO.OUT)
Set initial value for output: GPIO.setup(# of pin, GPIO.OUT, initial=GPIO.HIGH)
Reading input pin: GPIO.input(# of pin)
Writing to the output pin: GPIO.output(# of pin, state)

For more information and extra commands, check this link.

Tip
If you have used a pin in several scripts at the same time, you will see a warning when the code is executed. Use the following command to disable this alert: GPIO.setmode(GPIO.BCM)

Python GPIO Examples

LED

Circuit

Use resistor to connect a LED to GPIO17 pin.

raspberry-pi-gpio-led-circuit_fz

Code

  • Turning LED on and off with Gpiozero

  • Turning LED on and off with RPi.GPIO

  • Blinking LED w/ Gpiozero

  • Blinking LED w/ RPi.GPIO

  • LED with variable brightness w/ Gpiozero

  • Gpiozero (Method 2)

  • LED with variable brightness w/ RPi.GPIO

Button

Circuit

connect button to Pin2. Pin2 is always pulled up by default.

raspberry-pi-gpio-button-circuit_fz

Code

  • Check if a Button is pressed w/ Gpiozero

  • Check if a Button is pressed w/ RPi.GPIO

  • Run a function every time the button is pressed and released (w/ Gpiozero)

  • Shutdown Button w/ Gpiozero
    By pressing and holding the button for 2 seconds, your PC will shut down.

Button + LED

Circuit

Control a LED with a button

raspberry-pi-gpio-button-led-circuit_fz

Code (w/ Gpiozero)

Bargraph

Circuit

Note: Some bargraph models may need a resistor.

raspberry-pi-gpio-bargraph-circuit_fz

Code (w/ Gpiozero)

Turning a Buzzer On and Off w/ Raspberry Pi GPIO

Circuit

Code (w/ Gpiozero)

Control RGB LED Color w/ Raspberry Pi GPIO

Circuit

Code (w/ Gpiozero)

Controlling LDR w/ Raspberry Pi GPIO

If the environment is dark, the LED is on, otherwise the LED is off

Circuit

raspberry-pi-gpio-LDR-circuit_fz

Code (w/ Gpiozero)

What's Next?

  • Use two buttons to increase or decrease the number of bright LEDs. The first button turns an LED on and if the second button is press, one of the bright LEDs turns off.
  • Detect the motion using a motion sensor (PIR) and alarm the buzzer in case of motion.

Buy A Raspberry Pi Board

Share this post

Comments (6)

  • Michael Freeman Reply

    Hi,
    This was a great tutorial. Thank you!
    I am new to programing these devices and I was hoping if you could point me in the right direction.
    I am saving video feed to a micro sd card that needs to go through a Rasberry Pi and then through an Ethernet. The camera has a slot for a micro sd card. I plan on connected a male micro sd extender strip to the Pi’s GPIO pins (male end enters into camera and strip connects to GPIO) and coding the Pi to pull data from the camera and save to the Pi. Do you know of any libraries that are designed to do this?

    August 1, 2019 at 2:33 pm
    • Saeed Hosseini Reply

      Hello.
      We are glad for your interest in this project.
      That’s a cool idea.
      Unfortunately, we don’t know any proper lib for your project.

      August 5, 2019 at 5:34 am
  • Vilk Reply

    r u sure graph for Button + LED is correct ?

    September 9, 2019 at 12:10 pm
    • Saeed Hosseini Reply

      Hi, yes they are all correct.

      September 19, 2019 at 4:03 am
  • Will Reply

    I can’t see if the button used is normally open or normally closed. Could you clarify please.

    October 19, 2019 at 6:45 pm
    • Saeed Hosseini Reply

      the button is normally open

      October 21, 2019 at 5:57 am

Leave a Reply

Your email address will not be published. Required fields are marked *