2. Introduction
Topics covered:
1. Background
2. The Raspberry Pi
3. The Toradex Colibri and Aster Carrier Board
4. The GPIO Learning Board
5. Using the Sysfs Interface
6. Python Programming
7. C/C++ Programming with Sysfs
8. C/C++ Programming with WiringPi
9. Where to Go Next
10. References
2
3. Background
What is GPIO?
A GPIO or General-Purpose Input/Output is a signal pin on an integrated circuit or
board that can be used by the user for perform digital input or output functions. By
definition it has no predefined purpose and can be used by the hardware or
software developer to perform functions that they choose. Typical applications
include controlling LEDs, reading switches, and controlling various types of
sensors.
3
4. Background
● GPIO may be implemented by dedicated integrated circuits.
● More often directly supported by system on a chip (SoC) or system on a
module (SoM) devices.
● Most common functions of GPIO pins:
● Configurable in software to be input or output
● Can be enabled or disabled
● Setting the value of a digital output
● Reading the value of a digital input
● Generating an interrupt when the input changes value
● GPIO pins are digital, meaning they only support high/low or on/off levels.
● Generally don't support analog input or output with many discrete voltage
levels.
● Some GPIO pins may also directly support standardized communication
protocols like serial communication, SPI, I2
C, PCM, and PWM.
4
5. Background
Recommended parts and tools for learning:
● GPIO breakout cable or prototyping board
● Solderless breadboard and jumper wires
● Variety of LEDs, resistors, and switches
● Low-cost digital multimeter
5
6. Background
Safety:
● Voltages on embedded boards are typically low (5 volts or less).
● Risk of electric shock is minimal, as long as you avoid any circuitry that
operates on power line voltages.
● Use caution and wear eye protection if you do any soldering or clip wire leads.
● Most likely accident is to inadvertently damage embedded board. Connecting
a GPIO or other pin to the wrong voltage can easily damage the board and
render it unusable.
● Static electricity, especially during the dry winter months, can also generate
high voltages that can damage hardware if you develop a static charge and
then touch it. Grounded antistatic mat and/or wrist strap is recommended for
your work area.
6
7. Background
In real-world embedded programing, generally you don’t want to do any significant
amount of GPIO programming on the same CPU as the one that runs the GUI. You
will typically want to do that on another processor or microcontroller, particularly if
there are any real-time requirements for controlling the hardware.
Some exceptions to this rule can include:
1. Low speed or rarely used functions (like power on/off switch sensing).
2. Designs where you are using a real-time operating system (RTOS) and can run
code from a process or thread with guaranteed response and latency times.
3. Developing an initial prototype or proof of concept with an off-the-shelf board
like the Raspberry Pi that is not meant for production use.
4. Educational or self-learning applications where performance is not a factor.
7
8. The Raspberry Pi
● Family of low cost single-board computers developed primarily for education
by the non-profit Raspberry Pi Foundation.
● Over 25 million units shipped.
● Current models have 40-pin header connector that provides access to the
GPIO pins and some other signals.
● Access to 26 GPIO pins as well as 5V, 3.3V, ground, and some specialized pins
for an ID EEPROM function.
● 26 GPIO pins can be individually configured as inputs or outputs, and use 3.3V
logic levels where a HIGH logic level is represented as nominally 3.3 volts and
a LOW by zero volts.
● Cannot tolerate higher voltages (like 5 volts) without being damaged.
8
9. The Raspberry Pi
● Most pins can be configured to connect internal pullup or pulldown resistors
(unconnected inputs typically have an undefined logic level).
● Also support for PWM, SPI, I2
C, and serial on specific pins.
● Important to distinguish between the GPIO pin numbers (e.g. GPIO14) and the
physical pin numbers.
● Under Raspbian, normal users (e.g. "pi") are usually member of group "gpio"
and can access without being root.
● raspi-config program can enable some additional GPIO options (see
"Interfacing Options").
9
10. Toradex Colibri and Aster Carrier Board
● Colibri is a SOM in a SIM format.
● Aster carrier board buffers and brings signals out to suitable connectors.
● Carrier board has a Raspberry Pi compatible GPIO header.
● Also Arduino compatible "shield" connectors.
● GPIO pin names are different from Raspberry Pi.
● Only certain GPIO pins are available with default kernel device tree.
10
11. The GPIO Learning Board
● To facilitate some hands-on labs, ICS designed a small board.
● Connects to a Raspberry Pi (or compatible) computer's GPIO connector and
provides some simple functions for experimenting with GPIO programming.
● Functions provided are:
● Red, green, and yellow LEDs which can be individually turned on or off.
● A pushbutton whose status can be read.
● DHT11 or DHT22 temperature/humidity sensor (unpopulated socket).
● Connector for an FTDI USB to serial adaptor which provides access to the serial port/console.
● Compatible with the Raspberry Pi 2 or later (Raspberry Pi version 1 has a
smaller GPIO connector). Works with Raspberry Pi Zero if it has a GPIO
header installed.
● Compatible with the GPIO connector on a Toradex Colibri i.MX6 series
mounted on an Aster carrier board.
11
13. The GPIO Learning Board
Raspberry Pi 0/2/3/4:
13
Function P1 Pin GPIO Name
Red LED 18 GPIO24
Green LED 22 GPIO25
Yellow LED 29 GPIO5
Pushbutton 31 GPIO6
DHT11/22 37 GPIO26
14. The GPIO Learning Board
Toradex i.MX6 series Colibri SOM with Aster carrier board:
14
Function P1 Pin GPIO Name
Red LED 18 GPIO52
Green LED 22 GPIO53
Yellow LED 29 GPIO63
Pushbutton 31 GPIO93
DHT11/22 37 GPIO51
15. Using the Sysfs Interface
● Different ways to access GPIO hardware from programs.
● Sysfs is a simple one supported by the Linux kernel and makes devices visible
in the file system.
● GPIO hardware exposed in the file system under /sys/class/gpio.
● Can experiment from the command line without needing to write any code.
15
16. Using the Sysfs Interface
Basic steps to use a GPIO pin from the sysfs interface:
1. Export the pin.
2. Set the pin direction (input or output).
3. If an output pin: set the level to low or high.
4. If an input pin: read the pin's level (low or high).
5. When done, unexport the pin.
16
17. Using the Sysfs Interface
Exporting:
● To export a pin, write the pin name/number to the pseudo file
/sys/class/gpio/export
● Indicates that we want to use a specific GPIO pin and makes it visible in the
sysfs file system hierarchy.
● Later when we are done, we can unexport the pin.
● Needing to explicitly export a pin can help prevent errors where one might
inadvertently attempt to access the wrong pin.
17
18. Using the Sysfs Interface
Example:
$ ls /sys/class/gpio/
export gpiochip0 gpiochip128 gpiochip160 gpiochip192 gpiochip32
gpiochip64 gpiochip96 unexport
$ echo 52 >/sys/class/gpio/export
$ ls /sys/class/gpio/
export gpio52 gpiochip0 gpiochip128 gpiochip160 gpiochip192
gpiochip32 gpiochip64 gpiochip96 unexport
18
19. Using the Sysfs Interface
Setting pin direction:
● Set the pin to be either an input or an output.
● Done by writing either "in", or "out" to the direction file.
19
20. Using the Sysfs Interface
Example (input):
$ echo in >/sys/class/gpio/gpio52/direction
Example (output):
$ echo out >/sys/class/gpio/gpio52/direction
$ cat /sys/class/gpio/gpio52/direction
out
20
21. Using the Sysfs Interface
Setting level of an output pin:
● Write the value 0 or 1 (corresponding to low or high) to the value file for the
pin.
21
22. Using the Sysfs Interface
Example (set to low level):
$ echo 0 >/sys/class/gpio/gpio52/value
Example (set to high level):
$ echo 1 >/sys/class/gpio/gpio52/value
22
23. Using the Sysfs Interface
Reading level of an input pin:
● Can read value using the same "value" file.
Example:
$ cat /sys/class/gpio/gpio52/value
0
23
24. Using the Sysfs Interface
Unexporting a pin:
● When finished using the GPIO pin, unexport it.
● Just write the pin name to the unexport file.
24
25. Using the Sysfs Interface
Example:
$ echo 52 >/sys/class/gpio/unexport
$ ls /sys/class/gpio
export gpiochip0 gpiochip128 gpiochip160
gpiochip192 gpiochip32 gpiochip64 gpiochip96 unexport
25
26. Using the Sysfs Interface
Doing More:
● More functions that can be done with GPIO pins that aren't easily done from
the sysfs interface.
● e.g. pullup, pulldown resistors, PWM modes.
26
27. Lab: Toggle an LED
● Use sysfs interface to toggle the red LED on and off.
● Put the commands in a shell script (make executable).
● See earlier slides for GPIO pin names.
● Hint: use sleep or usleep for delays.
Bonus:
● Toggle the other LEDs.
● Make an interesting pattern.
27
28. Lab: Toggle an LED - Solution
#!/bin/sh
echo 52 >/sys/class/gpio/export
echo out >/sys/class/gpio/gpio52/direction
while true
do
echo 0 >/sys/class/gpio/gpio52/value
usleep 200000
echo 1 >/sys/class/gpio/gpio52/value
usleep 200000
done
28
29. Lab: Read Pushbutton Status
● Use sysfs interface to read the pushbutton status.
● Put the commands in a shell script.
● Bonus: toggle an LED based on the pushbutton status.
29
30. Lab: Read Pushbutton Status - Solution
#!/bin/sh
echo 93 >/sys/class/gpio/export
echo in >/sys/class/gpio/gpio93/direction
while true
do
echo -n "switch = "
cat /sys/class/gpio/gpio93/value
usleep 200000
done
30
31. Python Programming
● Fast growing and popular programming language.
● "Pi" in Raspberry Pi standards for "Python Interpreter".
● Many advantages: interpreter, clean syntax, many add-on modules.
● Downsides include performance and resource requirements.
● Qt now has fully supported Python bindings.
● True embedded applications usually use C or C++.
● Popular Python modules for GPIO include RPi.GPIO and Gpiozero.
31
32. Python Programming - Rpi.GPIO Example
#!/usr/bin/python3
import RPi.GPIO as GPIO
import time
led = 18
switch = 31
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led, GPIO.OUT)
GPIO.setup(switch, GPIO.IN)
for i in range(10):
GPIO.output(led, GPIO.HIGH)
time.sleep(0.2)
GPIO.output(led, GPIO.LOW)
time.sleep(0.2)
print('Switch status = ', GPIO.input(switch))
GPIO.cleanup()
32
33. Python Programming - Gpiozero Example
#!/usr/bin/python3
from gpiozero import LED, Button
from signal import pause
led = LED(24)
button = Button(6)
button.when_pressed = led.on
button.when_released = led.off
pause()
33
34. C/C++ Programming with Sysfs
● Can use the sysfs interface to program GPIO from C or C++.
● open files, read and write.
● Advantages: simple, portable.
● Disadvantages: low level API, limited performance.
34
35. Lab: C Programming with Sysfs
Lab: C Programming with Sysfs
● Write a C or C++ program to toggle the red LED at a 100 millisecond rate for
10 seconds and then exit.
● Follow similar steps as the shell script version.
● Hint: Use standard library functions open(), read(), write(), close().
● Hint: Can use usleep() for delays.
● Or use Qt equivalents if desired.
35
37. Lab: C Programming with Sysfs
int main()
{
std::string pin = "24"; // Pin 24 on Raspberry Pi
// Paths for GPIO sysfs access.
std::string exprt = "/sys/class/gpio/export";
std::string unexport = "/sys/class/gpio/unexport";
std::string direction = "/sys/class/gpio/gpio" + pin + "/direction";
std::string value = "/sys/class/gpio/gpio" + pin + "/value";
// Export the desired pin by writing to /sys/class/gpio/export
int fd = open(exprt.c_str(), O_WRONLY, 0);
write(fd, pin.c_str(), 2);
close(fd);
// Set the pin to be an output by writing "out" to /sys/class/gpio/gpioXX/direction
fd = open(direction.c_str(), O_WRONLY, 0);
write(fd, "out", 3) != 3);
close(fd);
37
38. Lab: C Programming with Sysfs
fd = open(value.c_str(), O_WRONLY, 0);
// Toggle LED 50 ms on, 50ms off, 100 times (10 seconds)
for (int i = 0; i < 100; i++) {
write(fd, "1", 1);
usleep(50000);
write(fd, "0", 1);
usleep(50000);
}
close(fd);
// Unexport the pin by writing to /sys/class/gpio/unexport
fd = open(unexport.c_str(), O_WRONLY, 0);
write(fd, pin.c_str(), 2)
close(fd);
// And exit
return 0;
}
38
39. C/C++ Programming with WiringPi - Example
#include <wiringPi.h>
int main(void)
{
const int led = 5; // Red LED: phys. pin 18, BCM GPIO24, WiringPi pin 5.
wiringPiSetup();
pinMode(led, OUTPUT);
while (1) {
digitalWrite(led, HIGH);
delay(500);
digitalWrite(led, LOW);
delay(500);
}
return 0;
}
39
40. Lab: GPIO Version of QML Traffic Light
These are four examples/demos based on on the QML traffic light example. They
add GPIO support using LEDs and pushbutton. Examine the source code to for
each to understand how it works. Build and run it. Try making some changes.
LightControl:
● QML traffic light example extended to drive hardware LEDs through GPIO.
ButtonPolling:
● Extends example to read pushbutton for pedestrian.
● Polls pushbutton status every 10 ms.
40
41. Lab: GPIO Version of QML Traffic Light
ButtonInterrupt:
● Uses QSocketNotifier to emit a signal when button state changes.
● Avoids overhead of polling.
ButtonDebounce:
● Extends ButtonInterrupt by "debouncing" change in button state.
● Waits 50 ms after state change before returning from handler.
● See GpioIn::updateGpio()
41
42. Where To Go Next
Serial Communications
● Serial/UART standards like RS-232, RS-422, RS-485.
● Asynchronous serial interfaces, send one bit at a time.
● Need to agree on baud rate, data bits, start/stop bits, parity.
● RS-232 uses voltage levels of +/- 3-15V.
● RS-422 is differential signalling, longer distance.
● RS-485 supports multi-point.
● Also higher level protocols built on serial like CAN bus and Modbus
● Some USB devices are serial devices (e.g. FTDI).
● On newer computers can use USB to serial converter.
● GPIO Learning Board has connector for USB to serial FTDI to board’s serial
port. Can be configured as a console or just used as a serial port.
42
43. Where To Go Next
PWM:
● Pulse Width Modulation.
● Used for controlling servos, D/A conversion, audio effects.
● Many SOCs and SOMs have hardware support for PWM that is much more
efficient than implementing in software.
43
44. Where To Go Next
SPI:
● Serial Peripheral Interface or SPI bus.
● Also known as SSI (Synchronous Serial Interface).
● Full duplex, synchronous, serial data link.
● Four-wire serial bus.
● Often used with sensors and SD cards.
● Devices communicate in master/slave mode.
● Multiple slave devices are allowed with individual slave select lines.
44
45. Where To Go Next
I2
C:
● I²C (Inter-Integrated Circuit), pronounced I-squared-C or I-two-C.
● Multi-master, multi-slave, single-ended, serial computer bus invented by
Philips Semiconductor.
● Used for attaching low-speed peripherals to computer motherboards and
embedded systems.
● Uses two bidirectional open-drain lines, Serial Data Line (SDA) and Serial
Clock Line (SCL), pulled up with resistors.
● Typical voltages used are 5V or 3.3V, although other voltages are permitted.
45
46. Where To Go Next
One-Wire Protocol:
● Device communications bus system designed by Dallas Semiconductor
(sometimes called Dallas 1 Wire).
● Provides low-speed data, signalling, and power over a single signal.
● Master and slave devices.
● Similar to I²C, but with lower data rates and longer range.
● Typically used to communicate with small inexpensive devices such as digital
thermometers and weather instruments.
● Only two wires: data and ground. Device also powered by data line.
● Can be supported on Linux using GPIO and bit banging.
46
47. Where To Go Next
Bit-banging:
● Refers to implementing protocols in software using GPIO pins.
● Some devices use proprietary protocols, e.g, DHT11 or DHT22
temperature/humidity sensor.
● Can be controlled over one wire using bit-banging techniques.
● Can do more complex protocols depending on resource requirements.
47
48. Where To Go Next
libgpiod:
● GPIO sysfs interface is deprecated in favor of a new character device API.
● New interface guarantees all allocated resources are freed after closing the
device file descriptor and adds several new features that are not present in
the obsolete sysfs interface (like event polling, setting/reading multiple values
at once and open-source and open-drain GPIOs).
● Hard to use directly, so a library is provided that encapsulates the ioctl calls
and data structures behind a straightforward API.
● Also contains a set of command-line tools that should allow an easy
conversion of user scripts to using the character device.
● At the current time, library is not well documented and device tree support for
the pin names is not there yet for Raspberry Pi (Raspbian) or Toradex (Yocto)
48
49. Homework Project: Temperature/Humidity Sensor
● For a more challenging programming project, read a DHT11/DHT22
temperature/humidity sensor using bit banging techniques.
● There is a socket to install one on the GPIO Learning Board.
● Cost: $5 (DHT11) - $10 (DHT22)
● See data sheet for the protocol.
● Or look for third party libraries or code to use.
49