9. GPIO

The Raspberry Pi has General Purpose Input Output pins. This guide will give an short insight into controlling the GPIO pins on the Raspberry Pi using a Python library called GPIOzero.

  1. Materials needed
  2. GPIO pinout
  3. Analog vs. Digital
  4. Blink
  5. LED PWM
  6. Button
  7. Combining everything

Your Raspberry Pi is more than just a small computer, it is a hardware prototyping tool! The RPi has bi-directional I/O pins, which you can use to drive LEDs, spin motors, or read button presses. To drive the RPi’s I/O lines requires a bit or programming. You can use a variety of programing languages, but we decided to use a really solid, easy language for driving I/O: Python.

9.2. GPIO Pinout

Raspberry has its GPIO over a standard male header on the board. From the first models to the latest, the header has expanded from 26 pins to 40 pins while maintaining the original pinout.

../_images/rpi_old_new_pin.jpg

There are (at least) two, different numbering schemes you may encounter when referencing Pi pin numbers:

  1. Broadcom (SoC) chip-specific pin numbers.
  2. P1 physical pin numbers.

You can use either number-system, but when you are programming how to use the pins, it requires that you declare which scheme you are using at the very beginning of your program. We will see this later.

The next table shows all 40 pins on the P1 header, including any particular function they may have, and their dual numbers:

../_images/header_pinout.jpg

In the next table, we show another numbering system along with the ones we showed above: Pi pin header numbers and element14 given names, wiringPi numbers, Python numbers, and related silkscreen on the wedge. The Broadcom pin numbers in the table are related to RPi Model 2 and later only.

../_images/pi_pin_header_numbers.png

This table shows that the RPi not only gives you access to the bi-directional I/O pins, but also

Tip

There is a useful online guide for finding the assignment and numbering of each pin, along with other guides, that you may find useful at: pinout.xyz

9.2.1. Analog vs. Digital

Before starting with our practise, we will revise the difference between analog and digital signals. Both are used to transmit information, usually through electric signals. In both these technologies, the information, such as any audio or video, is transformed into electric signals. The difference between analog and digital:

  • In analog technology, information is translated into electric pulses of varying amplitude.
  • In digital technology, translation of information is into binary format (zero or one) where each bit is representative of two distinct amplitudes.
../_images/analog_digital.png

9.2.1.1. Comparison chart

Analogue Digital
Signal Analog signal is a continuous signal which represents physical measurements. Digital signals are discrete time signals generated by digital modulation.
Waves Denoted by sine waves. Denoted by square waves.
Representation Uses continuous range of values to represent information. Uses discrete or discontinuous values to represent information.
Example Human voice in air, analog electronic devices. Computers, CDs, DVDs, and other digital electronic devices.
Technology Analog technology records waveforms as they are. Samples analog waveforms into a limited set of numbers and records them.
Data transmissions Subjected to deterioration by noise during transmission and write/read cycle. Can be noise-immune without deterioration during transmission and write/read cycle.
Response to Noise More likely to get affected reducing accuracy. Less affected since noise response are analog in nature.
Flexibility Analog hardware is not flexible. Digital hardware is flexible in implementation.
Uses Can be used in analog devices only. Best suited for audio and video transmission. Best suited for Computing and digital electronics.
Applications Thermometer. PCs, PDAs.
Bandwidth Analog signal processing can be done in real time and consumes less bandwidth. There is no guarantee that digital signal processing can be done in real time and consumes more bandwidth to carry out the same information.
Memory Stored in the form of wave signal. Stored in the form of binary bit.
Power Analog instrument draws large power. Digital instrument draws negligible power.
Cost Low cost and portable. Cost is high and not easily portable.
Impedance Low High order of 100 megaohms
Errors Analog instruments usually have a scale which is cramped at lower end and give considerable observational errors. Digital instruments are free from observational errors like parallax and approximation errors.

9.4. LED PWM

Use the same layout for the electronics as before.

9.4.1. What is PWM?

Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means. Digital control is used to create a square wave, a signal switched between on and off. This on-off pattern can simulate voltages in between full on (3.3 Volts for RPi and 5 Volts for Arduino) and off (0 Volts) by changing the portion of the time the signal spends on versus the time that the signal spends off. The duration of “on time” is called the pulse width. To get varying analog values, you change, or modulate, that pulse width. If you repeat this on-off pattern fast enough with an LED for example, the result is as if the signal is a steady voltage between 0 and 5v controlling the brightness of the LED.

Hint

For more information check out this link.

9.4.2. The Code

Repeat the same steps of “Blink” to upload the code below, this time call the file led-pwm.py and save it in the code folder that we have previously created. It’s up to you to make the code executable or not.

#!/usr/bin/env python

from gpiozero import PWMLED
from time import sleep

led = PWMLED(17)

while True:
    led.value = 0  # off
    sleep(1)
    led.value = 0.5  # half brightness
    sleep(1)
    led.value = 1  # full brightness
    sleep(1)

9.4.3. Understanding “LED PWM” code

The main difference here is that we are using the class PWMLED instead of the class LED. The PWMLED class has an extra parameter that we can tweak which is value. value indicates the duty cycle of this PWM device. 0.0 is off, 1.0 is fully on. Values in between may be specified for varying levels of power in the device.

9.5. Button

9.5.1. Hardware Setup

We start assembling the circuit as shown in the diagram below.

../_images/button-wiring.png

9.5.2. The Code

Repeat the same steps of “Blink” to upload the code below, this time call the file button.py and save it in the code folder that we have previously created. It’s up to you to make the code executable or not.

#!/usr/bin/env python

from gpiozero import Button

button = Button(2)  # we first create an instance of the Button class
buttonWasPressed = False # 1st flag will help us track if the button was pressed in the last loop
buttonWasReleased = False # 2nd flag will help us track if the button was released in the last loop

while True:

    if button.is_pressed:
        buttonWasReleased = False  # reset back to false since the button is now being pressed

        # we only want the print() code to be run once,
        # so if it was pressed the last time the code looped, don't print it this time!
        if not buttonWasPressed:
            print("Button is pressed")

            # since we have now run this code, we don't want
            # it to run the next time the code loops, so
            buttonWasPressed = True

    else:
        # this code is run when the button is not being pressed
        buttonWasPressed = False
        if not buttonWasReleased:
            print("Button is released")
            buttonWasReleased = True

9.5.3. Understanding “Button” code

Here we are using the class Button from GPIOzero. This class has many functions and parameter, so make sure you check out the reference. Here we are using the is_pressed property of the class. is_pressed returns True if the device is currently active and False otherwise.

In this example, we also introduce the concept of flags. Flags are a way to help us keep track of the binary state of a particular thing by storing them as boolean variables (1/0 or True/False). In this case, we need to keep track of the binary state of whether the button is was pressed, and the binary state of whether the button was released.

Note

We need to keep track of the actions that occurred, not the state of the button itself as this is already monitored is_pressed property of the Button() class.

In the code above, we use these flags to prevent the repetition of a print statement. i.e. If we did not have them, then the “Button is released” statement would print repetitively until the button was pressed, and vice versa.

Flags allow us to ensure the print statement is only printed on the first iteration of the loop. Every iteration thereafter will skip the print statement. This occurs until there is a change in the is_pressed property, at which point the respective flag is reset to False.

9.6. Combining Everything

Now we challenge you to combine all the previous three scripts to create one. Make the script in order that:

  • when the button is pressed one of the two LEDs fades to 25% of its brightness and the other one blinks once
  • when the button is released the PWM LED goes back to 100% brightness.

9.6.1. Hardware Setup

We start assembling the circuit as shown in the diagram below.

../_images/practise_1.png

9.6.2. Code Tips

Use the when_pressed and when_released properties of the Button class. You can find the code to control one LED with the button, here.

Acknowledgements