SlideShare a Scribd company logo
1 of 51
Download to read offline
GPIO Programming
1
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
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
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
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
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
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
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
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
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
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
The GPIO Learning Board
12
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Lab: C Programming with Sysfs
● See solution in GPIO/sol-toggleled
36
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
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
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
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
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
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
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
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
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
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
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
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
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
References
1. https://www.raspberrypi.org/documentation/usage/gpio
2. https://www.ics.com/blog/introduction-gpio-programming
3. https://github.com/tranter/webinars/tree/master/GPIO
4. https://github.com/jefftranter/raspberrypi/tree/master/gpio-board
5. https://www.kernel.org/doc/Documentation/gpio/sysfs.txt
6. https://developer.toradex.com/knowledge-base/how-to-use-gpio-library
7. https://developer.toradex.com/knowledge-base/gpio-lib-api
8. https://developer.toradex.com/knowledge-base/gpio-(linux)
9. http://jackmitch.github.io/libsoc/
10. https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git
50
GPIO Programming
Questions?
51

More Related Content

What's hot

What's hot (20)

Introduction to Internet of Things Hardware
Introduction to Internet of Things HardwareIntroduction to Internet of Things Hardware
Introduction to Internet of Things Hardware
 
I2c protocol - Inter–Integrated Circuit Communication Protocol
I2c protocol - Inter–Integrated Circuit Communication ProtocolI2c protocol - Inter–Integrated Circuit Communication Protocol
I2c protocol - Inter–Integrated Circuit Communication Protocol
 
Introduction to stm32-part1
Introduction to stm32-part1Introduction to stm32-part1
Introduction to stm32-part1
 
Introduction to ARM LPC2148
Introduction to ARM LPC2148Introduction to ARM LPC2148
Introduction to ARM LPC2148
 
Part-2: Mastering microcontroller with embedded driver development
Part-2: Mastering microcontroller with embedded driver developmentPart-2: Mastering microcontroller with embedded driver development
Part-2: Mastering microcontroller with embedded driver development
 
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWER
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWERMastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWER
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWER
 
UART
UART UART
UART
 
Introduction to Node MCU
Introduction to Node MCUIntroduction to Node MCU
Introduction to Node MCU
 
UART
UARTUART
UART
 
I2C Protocol
I2C ProtocolI2C Protocol
I2C Protocol
 
Serial Peripheral Interface
Serial Peripheral InterfaceSerial Peripheral Interface
Serial Peripheral Interface
 
General Purpose Input Output - Brief Introduction
General Purpose Input Output - Brief IntroductionGeneral Purpose Input Output - Brief Introduction
General Purpose Input Output - Brief Introduction
 
Architecture of 8085 microprocessor
Architecture of 8085 microprocessorArchitecture of 8085 microprocessor
Architecture of 8085 microprocessor
 
Part-1 : Mastering microcontroller with embedded driver development
Part-1 : Mastering microcontroller with embedded driver development Part-1 : Mastering microcontroller with embedded driver development
Part-1 : Mastering microcontroller with embedded driver development
 
44CON 2014 - Stupid PCIe Tricks, Joe Fitzpatrick
44CON 2014 - Stupid PCIe Tricks, Joe Fitzpatrick44CON 2014 - Stupid PCIe Tricks, Joe Fitzpatrick
44CON 2014 - Stupid PCIe Tricks, Joe Fitzpatrick
 
Actel fpga
Actel fpgaActel fpga
Actel fpga
 
Arm cortex-m4 programmer model
Arm cortex-m4 programmer modelArm cortex-m4 programmer model
Arm cortex-m4 programmer model
 
Introduction to stm32-part2
Introduction to stm32-part2Introduction to stm32-part2
Introduction to stm32-part2
 
Altera flex
Altera flexAltera flex
Altera flex
 
NodeMCU ESP8266 workshop 1
NodeMCU ESP8266 workshop 1NodeMCU ESP8266 workshop 1
NodeMCU ESP8266 workshop 1
 

Similar to Ins and Outs of GPIO Programming

Similar to Ins and Outs of GPIO Programming (20)

Atomic pi Mini PC
Atomic pi Mini PCAtomic pi Mini PC
Atomic pi Mini PC
 
Atomic PI apug
Atomic PI apugAtomic PI apug
Atomic PI apug
 
[5]投影片 futurewad樹莓派研習會 141218
[5]投影片 futurewad樹莓派研習會 141218[5]投影片 futurewad樹莓派研習會 141218
[5]投影片 futurewad樹莓派研習會 141218
 
Raspberry pi led blink
Raspberry pi led blinkRaspberry pi led blink
Raspberry pi led blink
 
Raspberry Pi GPIO Tutorial - Make Your Own Game Console
Raspberry Pi GPIO Tutorial - Make Your Own Game ConsoleRaspberry Pi GPIO Tutorial - Make Your Own Game Console
Raspberry Pi GPIO Tutorial - Make Your Own Game Console
 
F9 microkernel app development part 2 gpio meets led
F9 microkernel app development part 2 gpio meets ledF9 microkernel app development part 2 gpio meets led
F9 microkernel app development part 2 gpio meets led
 
Interfacing two wire adc0831 to raspberry pi2 / Pi3
Interfacing two wire adc0831 to raspberry pi2 / Pi3Interfacing two wire adc0831 to raspberry pi2 / Pi3
Interfacing two wire adc0831 to raspberry pi2 / Pi3
 
Raspberry Pi - HW/SW Application Development
Raspberry Pi - HW/SW Application DevelopmentRaspberry Pi - HW/SW Application Development
Raspberry Pi - HW/SW Application Development
 
PPT+.pdf
PPT+.pdfPPT+.pdf
PPT+.pdf
 
Project ACRN GPIO mediator introduction
Project ACRN GPIO mediator introductionProject ACRN GPIO mediator introduction
Project ACRN GPIO mediator introduction
 
Python-in-Embedded-systems.pptx
Python-in-Embedded-systems.pptxPython-in-Embedded-systems.pptx
Python-in-Embedded-systems.pptx
 
ELC North America 2021 Introduction to pin muxing and gpio control under linux
ELC  North America 2021 Introduction to pin muxing and gpio control under linuxELC  North America 2021 Introduction to pin muxing and gpio control under linux
ELC North America 2021 Introduction to pin muxing and gpio control under linux
 
Interfacing the Raspberry Pi to the World
Interfacing the Raspberry Pi to the WorldInterfacing the Raspberry Pi to the World
Interfacing the Raspberry Pi to the World
 
Raspberry pi technical documentation
Raspberry pi technical documentationRaspberry pi technical documentation
Raspberry pi technical documentation
 
Introduction to Raspberry Pi
Introduction to Raspberry PiIntroduction to Raspberry Pi
Introduction to Raspberry Pi
 
manual_2020_Cyber Physical System.pdf
manual_2020_Cyber Physical System.pdfmanual_2020_Cyber Physical System.pdf
manual_2020_Cyber Physical System.pdf
 
4. GPIO Access
4. GPIO Access4. GPIO Access
4. GPIO Access
 
Introduction To Raspberry Pi with Simple GPIO pin Control
Introduction To Raspberry Pi with Simple GPIO pin ControlIntroduction To Raspberry Pi with Simple GPIO pin Control
Introduction To Raspberry Pi with Simple GPIO pin Control
 
Getting started with Intel IoT Developer Kit
Getting started with Intel IoT Developer KitGetting started with Intel IoT Developer Kit
Getting started with Intel IoT Developer Kit
 
PL-3 LAB MANUAL
PL-3 LAB MANUALPL-3 LAB MANUAL
PL-3 LAB MANUAL
 

More from ICS

Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
ICS
 

More from ICS (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Practical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfPractical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdf
 
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
 
Overcoming CMake Configuration Issues Webinar
Overcoming CMake Configuration Issues WebinarOvercoming CMake Configuration Issues Webinar
Overcoming CMake Configuration Issues Webinar
 
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
Enhancing Quality and Test in Medical Device Design - Part 2.pdfEnhancing Quality and Test in Medical Device Design - Part 2.pdf
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
 
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdfDesigning and Managing IoT Devices for Rapid Deployment - Webinar.pdf
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
 
Quality and Test in Medical Device Design - Part 1.pdf
Quality and Test in Medical Device Design - Part 1.pdfQuality and Test in Medical Device Design - Part 1.pdf
Quality and Test in Medical Device Design - Part 1.pdf
 
Creating Digital Twins Using Rapid Development Techniques.pdf
Creating Digital Twins Using Rapid Development Techniques.pdfCreating Digital Twins Using Rapid Development Techniques.pdf
Creating Digital Twins Using Rapid Development Techniques.pdf
 
Secure Your Medical Devices From the Ground Up
Secure Your Medical Devices From the Ground Up Secure Your Medical Devices From the Ground Up
Secure Your Medical Devices From the Ground Up
 
Cybersecurity and Software Updates in Medical Devices.pdf
Cybersecurity and Software Updates in Medical Devices.pdfCybersecurity and Software Updates in Medical Devices.pdf
Cybersecurity and Software Updates in Medical Devices.pdf
 
MDG Panel - Creating Expert Level GUIs for Complex Medical Devices
MDG Panel - Creating Expert Level GUIs for Complex Medical DevicesMDG Panel - Creating Expert Level GUIs for Complex Medical Devices
MDG Panel - Creating Expert Level GUIs for Complex Medical Devices
 
How to Craft a Winning IOT Device Management Solution
How to Craft a Winning IOT Device Management SolutionHow to Craft a Winning IOT Device Management Solution
How to Craft a Winning IOT Device Management Solution
 
Bridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory TeamsBridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory Teams
 
IoT Device Fleet Management: Create a Robust Solution with Azure
IoT Device Fleet Management: Create a Robust Solution with AzureIoT Device Fleet Management: Create a Robust Solution with Azure
IoT Device Fleet Management: Create a Robust Solution with Azure
 
Basic Cmake for Qt Users
Basic Cmake for Qt UsersBasic Cmake for Qt Users
Basic Cmake for Qt Users
 
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
 
Qt Installer Framework
Qt Installer FrameworkQt Installer Framework
Qt Installer Framework
 
Bridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory TeamsBridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory Teams
 
Overcome Hardware And Software Challenges - Medical Device Case Study
Overcome Hardware And Software Challenges - Medical Device Case StudyOvercome Hardware And Software Challenges - Medical Device Case Study
Overcome Hardware And Software Challenges - Medical Device Case Study
 
User Experience Design for IoT
User Experience Design for IoTUser Experience Design for IoT
User Experience Design for IoT
 

Recently uploaded

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 

Ins and Outs of GPIO Programming

  • 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
  • 12. The GPIO Learning Board 12
  • 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
  • 36. Lab: C Programming with Sysfs ● See solution in GPIO/sol-toggleled 36
  • 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
  • 50. References 1. https://www.raspberrypi.org/documentation/usage/gpio 2. https://www.ics.com/blog/introduction-gpio-programming 3. https://github.com/tranter/webinars/tree/master/GPIO 4. https://github.com/jefftranter/raspberrypi/tree/master/gpio-board 5. https://www.kernel.org/doc/Documentation/gpio/sysfs.txt 6. https://developer.toradex.com/knowledge-base/how-to-use-gpio-library 7. https://developer.toradex.com/knowledge-base/gpio-lib-api 8. https://developer.toradex.com/knowledge-base/gpio-(linux) 9. http://jackmitch.github.io/libsoc/ 10. https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git 50