Raspberry Pi GPIO Practice
Raspberry Pi GPIO Practice
Raspberry Pi GPIO Practice
blog
Raspberry Pi
GPIO with Python
Hans-Petter Halvorsen
Free Textbook with lots of Practical Examples
https://www.halvorsen.blog/documents/programming/python/
Additional Python Resources
https://www.halvorsen.blog/documents/programming/python/
Contents
• Overview of GPIO
• LED
• PWM
• Push Button/Switch
• ADC (Analog to Digital Converter)
• TMP36
• ThingSpeak (Save Data to a Cloud Service)
Raspberry Pi
GPIO Pins
SD Card Ethernet
(the Back )
Camera
Connector USB A x 4
Raspberry PI GPIO
Hans-Petter Halvorsen
GPIO
Hans-Petter Halvorsen
GPIO Zero
• The GPIO Zero Python Library can be used to communicate
with GPIO Pins
• The GPIO Zero Python Library comes preinstalled with the
Raspberry Pi OS (so no additional installation is necessary)
Resources:
• https://www.raspberrypi.org/documentation/usage/gpio/p
ython/
• https://pypi.org/project/gpiozero/
• https://gpiozero.readthedocs.io/en/stable/
• https://gpiozero.readthedocs.io/en/stable/recipes.html
RPi.GPIO
• Rpi.GPIO is a module controlling the GPIO pins on the
Raspberry Pi
• RPi.GPIO is a more “low-level“ Python Library than
GPIO Zero. Actually, GPIO Zero is using RPi.GPIO
• The RPi.GPIO Python Library comes preinstalled with
the Raspberry Pi OS (so no additional installation is
necessary)
https://pypi.org/project/RPi.GPIO/
https://www.halvorsen.blog
LED
Hans-Petter Halvorsen
Necessary Equipment
• Raspberry Pi
• Breadboard
• LED
• Resistor, 𝑅 = 270Ω
• Wires (Jumper Wires)
Setup and Wiring
Raspberry Pi GPIO Pins
LED Example
LED
R=270Ω
pin = 16
led = LED(pin)
while True:
led.on()
sleep(1)
led.off()
sleep(1)
https://www.raspberrypi.org/documentation/usage/gpio/python/
LED Example
LED Example
from gpiozero import LED
This example turns a LED on/off 10 times from time import sleep
pin = 16
led = LED(pin)
N = 10
for x in range(N):
led.on()
sleep(1)
led.off()
sleep(1)
https://www.halvorsen.blog
PWM
Pulse Width Modulation
Hans-Petter Halvorsen
PWM
PWM is a digital (i.e., square wave) signal that oscillates according to a given frequency and
duty cycle.
The frequency (expressed in Hz) describes how often the output pulse repeats.
The period is the time each cycle takes and is the inverse of frequency.
The duty cycle (expressed as a percentage) describes the width of the pulse within that
frequency window.
https://www.electronicwings.com/raspberry-pi/raspberry-pi-pwm-generation-using-python-and-c
PWM as “Analog Out“
The Raspberry Pi has
no real Analog Out
pins, but we can use a
PWM pin.
PWM can be used to
control brightness of a
LED, control the speed
of a Fan, control a DC
Motor, etc.
GPIO Zero from time import sleep
import numpy as np
from gpiozero import PWMLED
PWM pin = 23
led = PWMLED(pin)
start = 0
stop = 1
step = 0.1
level = np.arange(start, stop, step)
for x in level:
led.value = x
sleep(1)
led.off()
RPi.GPIO
import time
import RPi.GPIO as GPIO
# Pin definitions
led_pin = 23
PWM GPIO.setmode(GPIO.BCM)
pwm.ChangeDutyCycle(10)
time.sleep(2)
pwm.ChangeDutyCycle(50)
time.sleep(2)
pwm.ChangeDutyCycle(90)
time.sleep(2)
Push Button
Hans-Petter Halvorsen
Necessary Equipment
• Raspberry Pi
• Breadboard
• Push Button
• LED
• Resistors, 𝑅 = 270Ω, 𝑅 = 10𝑘Ω
• Wires (Jumper Wires)
Setup and Wiring
Push Button/Switch
• Pushbuttons or switches connect two
points in a circuit when you press them.
• You can use it to turn on a Light when
holding down the button, etc.
Light
+ Switch (On/Off)
Battery
-
Button Setup
+3.3V
Using external Pull-up Resistor
Raspberry Pi GPIO Pins
GND
𝑅 = 10𝑘Ω
GPIO 16
Pull-up Resistor
+5V • When the pushbutton is open (unpressed)
there is a connection between 3.3/5V and
the DI pin.
Resistor
• This means the default state is True (High).
DI • When the button is closed (pressed), the
state goes to False (Low).
Switch
GND
Pull-up Resistor
True/High False/Low
+3.3/5V +3.3/5V
Resistor Resistor
DI DI
GND GND
Pull-down/Pull-up Resistor
Why do we need a pull-up or pull-down resistor in the
circuit?
• If you disconnect the digital I/O pin from everything, it
will behave in an irregular way.
• This is because the input is "floating" - that is, it will
randomly return either HIGH or LOW.
• That's why you need a pull-up or pull-down resistor in
the circuit.
Button Example
from gpiozero import Button
from time import sleep
pin = 16
button = Button(pin)
while True:
if button.is_pressed:
print("Pressed")
else:
print("Released")
In GPIO Zero, the default sleep(1)
configuration for a button is pull-up
https://www.raspberrypi.org/documentation/usage/gpio/python/
Button Example
# Pins definitions
btn_pin = 16
Here is the RPi.GPIO Python Library used
# Set up pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(btn_pin, GPIO.IN)
# Pins definitions
btn_pin = 16
# Set up pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(btn_pin, GPIO.IN)
N = 10
# If button is pushed, light up LED
try:
for x in range(N):
if GPIO.input(btn_pin):
print("Button Released")
else:
print("Button Pressed")
time.sleep(1)
Switch Switch
Open Closed
DI DI
GND GND
Button + LED Example
from gpiozero import LED, Button
from time import sleep
pin_btn = 16
button = Button(pin_btn)
pin_led = 23
led = LED(pin_led)
while True:
if button.is_pressed:
led.on()
else:
led.off()
sleep(1)
Button + LED Example
import time
import RPi.GPIO as GPIO
# Pin definitions
led_pin = 23
btn_pin = 16
# Suppress warnings
GPIO.setwarnings(False)
# Blink forever
while True:
if GPIO.input(btn_pin):
GPIO.output(led_pin, GPIO.LOW) # Turn LED off
else:
GPIO.output(led_pin, GPIO.HIGH) # Turn LED on
time.sleep(1)
https://www.halvorsen.blog
SPI
Serial Peripheral Interface (SPI)
Hans-Petter Halvorsen
SPI
• Serial Peripheral Interface (SPI)
• SPI is an interface to communicate with
different types of electronic components
like Sensors, Analog to Digital Converts
(ADC), etc. that supports the SPI
interface
• Thousands of different Components and
Sensors supports the SPI interface
https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/
Access SPI on Raspberry Pi
You need to Enable SPI on the Raspberry Pi
SPI Interface
SPI devices communicate in full duplex mode using a master-slave architecture with a
single master
Raspberry Pi SPI ADC, SPI Sensor, etc.
SCLK SCLK
MOSI MOSI
SPI Master SPI Slave
MISO MISO
CE CE
ADC
Analog to Digital Converter
Hans-Petter Halvorsen
ADC
• The Raspberry Pi has only Digital pins on the
GPIO connector
• If you want to use an Analog electric
component or an Analog Sensor together with
Raspberry Pi, you need to connect it through
an external ADC chip
• ADC – Analog to Digital Converter
https://en.wikipedia.org/wiki/Analog-to-digital_converter
MCP3002 ADC chip
The MCP3002 is a 10-bit analog to digital converter with 2 channels (0-1).
The MCP3002 uses a SPI Interface
http://ww1.microchip.com/downloads/en/DeviceDoc/21294E.pdf
https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-
raspberry-pi/experiment-3-spi-and-analog-input
Wiring
https://sites.google.com/a/joekamphaus.net/raspberry-pi-spi-interface-to-mcp3002/
Raspberry Pi GPIO Pins Wiring
+5V (Pin 2)
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the MCP3004/3204/3302
have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the channel attribute) is
read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value (for example,
when using an MCP3008 in differential mode, channel 0 is read relative to channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain devices operating
in differential mode).
https://gpiozero.readthedocs.io/en/stable/api_spi.html
Read Data from ADC
For test purpose we start by wiring a 1.5V Battery to the CH0 (+) and CH1(-) pins on the ADC
Note! WE have set differential=True (meaning CH0 is “+“ and CH1 is “-“)
from gpiozero import MCP3002
from time import sleep
TMP36
Temperature Sensor
Hans-Petter Halvorsen
TMP36 Temperature Sensor
A Temperature sensor like TM36 use a
solid-state technique to determine the
temperature.
https://learn.adafruit.com/tmp36-temperature-sensor
TMP36 Temperature Sensor
Convert form Voltage (V) to degrees Celsius
From the Datasheet we have:
N = 10
for x in range(N):
adcdata = adc.value #Value between 0 and 1
#print(adcdata)
sleep(1)
https://www.halvorsen.blog
ThingSpeak
Hans-Petter Halvorsen
ThingSpeak
• ThingSpeak is an IoT analytics platform service that lets you collect and
store sensor data in the cloud and develop Internet of Things
applications.
• The ThingSpeak service also lets you perform online analysis and act on
your data. Sensor data can be sent to ThingSpeak from any hardware
that can communicate using a REST API
• ThingSpeak has a Web Service (REST API) that lets you collect and store
sensor data in the cloud and develop Internet of Things applications (it
also has MQTT API).
• https://thingspeak.com
• Python Library for ThingSpeak: https://pypi.org/project/thingspeak/
ThingSpeak
ThingSpeak Write
import thingspeak
import time
channel_id = xxxxxx
write_key = "xxxxxxxxxxxxxxxxx"
N = 10
for x in range(N):
temperature = 24
response = channel.update({'field1': temperature})
time.sleep(15)
channel_id = xxxxxxx
write_key = ”xxxxxxxxxxxxxxxxxx”
N = 10
for x in range(N):
#Get Sensor Data
adcdata = adc.value #Scaled Value between 0 and 1
voltvalue = adcdata * 5 # Value between 0V and 5V
tempC = 100*voltvalue-50 # Temperature in Celsius
tempC = round(tempC,1)
print(tempC)
#Write to ThingSpeak
response = channel.update({'field1': tempC})
time.sleep(15)
Write TMP36 Data
Here we see the Temperature Data in ThingSpeak:
ThingSpeak Read
import thingspeak
channel_id = xxxxxx
read_key = ”xxxxxxxxxxxxxxxx"
#data = channel.get({})
data = channel.get_field({”field1"})
print(data)
https://thingspeak.readthedocs.io/en/latest/api.html
Additional Python Resources
https://www.halvorsen.blog/documents/programming/python/
Hans-Petter Halvorsen
University of South-Eastern Norway
www.usn.no
E-mail: [email protected]
Web: https://www.halvorsen.blog