0% found this document useful (0 votes)
2 views68 pages

Raspberry Pi GPIO With Python

Uploaded by

Rupesh Sushir
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views68 pages

Raspberry Pi GPIO With Python

Uploaded by

Rupesh Sushir
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link]

blog

Raspberry Pi
GPIO with Python
Hans-Petter Halvorsen
Free Textbook with lots of Practical Examples

[Link]
Additional Python Resources

[Link]
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

Power Supply (USB C) micro HDMI x 2


[Link]

Raspberry PI GPIO

Hans-Petter Halvorsen
GPIO

A powerful feature of the Raspberry Pi is the GPIO (general-purpose input/output) pins.


The Raspberry Pi has a 40-pin GPIO header as seen in the image
GPIO Features
The GPIO pins are Digital Pins which are either True
(+3.3V) or False (0V). These can be used to turn on/off
LEDs, etc.
The Digital Pins can be either Output or Input.
In addition, some of the pins also offer some other
Features:
• PWM (Pulse Width Modulation)
Digital Buses (for reading data from Sensors, etc.):
• SPI
• I2C
GPIO
[Link]

GPIO with Python

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:
• [Link]
ython/
• [Link]
• [Link]
• [Link]
[Link]
• [Link] is a module controlling the GPIO pins on the
Raspberry Pi
• [Link] is a more “low-level“ Python Library than
GPIO Zero. Actually, GPIO Zero is using [Link]
• The [Link] Python Library comes preinstalled with
the Raspberry Pi OS (so no additional installation is
necessary)

[Link]
[Link]

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Ω

GND (Pin 32)

GPIO16 (Pin 36)


Breadboard
LED Example
This Example “Runs for ever“ from gpiozero import LED
from time import sleep

pin = 16
led = LED(pin)

while True:
[Link]()
sleep(1)
[Link]()
sleep(1)

[Link]
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):
[Link]()
sleep(1)
[Link]()
sleep(1)
[Link]

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.

You can adjust the duty cycle


to increase or decrease the
average "on" time of the
signal. The following diagram
shows pulse trains at 0%,
25%, and 100% duty:
Controlling LED Brightness using PWM
• We've seen how to turn an LED on and off, but how do
we control its brightness levels?
• An LED's brightness is determined by controlling the
amount of current flowing through it, but that requires a
lot more hardware components.
• A simple trick we can do is to flash the LED faster than
the eye can see!
• By controlling the amount of time the LED is on versus
off, we can change its perceived brightness.
• This is known as Pulse Width Modulation (PWM).
[Link]
Controlling LED Brightness using PWM
Below we see how we can use PWM to control the brightness of a LED

[Link]
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 = [Link](start, stop, step)

for x in level:
[Link] = x
sleep(1)

[Link]()
[Link]
import time
import [Link] as GPIO

# Pin definitions
led_pin = 23

# Use "GPIO" pin numbering

PWM [Link]([Link])

# Set LED pin as output


[Link](led_pin, [Link])

# Initialize pwm object with 50 Hz and 0% duty cycle


pwm = [Link](led_pin, 50)
[Link](0)

[Link](10)
[Link](2)
[Link](50)
[Link](2)
[Link](90)
[Link](2)

# Stop, cleanup, and exit


[Link]()
[Link]()
[Link]

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

Switch We Push the Button Switch


Open Closed

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
[Link]
Button Example

In GPIO Zero, the default


configuration for a button is pull-up
We have wired according to pull-up.
This means:
Button Pressed -> True
Button Not Pressed -> False
Button Ex.2
import time
import [Link] as GPIO

# Pins definitions
btn_pin = 16
Here is the [Link] Python Library used
# Set up pins
[Link]([Link])
[Link](btn_pin, [Link])

# If button is pushed, light up LED


In [Link], the default configuration try:
for a button is pull-down while True:
if [Link](btn_pin):
print("Button Released")
We have wired according to pull-up. else:
This means: print("Button Pressed")
[Link](1)
Button Pressed -> False
Button Not Pressed -> True # When you press ctrl+c, this will be called
finally:
[Link]()
Button Example2
Button Ex.3
import time
import [Link] as GPIO

# Pins definitions
btn_pin = 16

# Set up pins
[Link]([Link])
[Link](btn_pin, [Link])

N = 10
# If button is pushed, light up LED
try:
for x in range(N):
if [Link](btn_pin):
print("Button Released")
else:
print("Button Pressed")
[Link](1)

# When you press ctrl+c, this will be


called
finally:
[Link]()
Button Example3
Pull-down Resistor
We could also have wired according to a “Pull-down“ Resistor
False/Low True/High
+3.3/5V +3.3/5V

Switch Switch
Open Closed

DI DI

We Push the Button


Resistor Resistor

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:
[Link]()
else:
[Link]()
sleep(1)
Button + LED Example
import time
import [Link] as GPIO

# Pin definitions
led_pin = 23
btn_pin = 16

# Suppress warnings
[Link](False)

# Use "GPIO" pin numbering


[Link]([Link])
# Set Button pin as input
[Link](btn_pin, [Link])
# Set LED pin as output
[Link](led_pin, [Link])

# Blink forever
while True:
if [Link](btn_pin):
[Link](led_pin, [Link]) # Turn LED off
else:
[Link](led_pin, [Link]) # Turn LED on

[Link](1)
[Link]

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
[Link]
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

The SPI bus specifies four logic signals:


• SCLK: Serial Clock (output from master)
• MOSI: Master Out Slave In (data output from master)
• MISO: Master In Slave Out (data output from slave)
• CE (often also called SS - Slave Select): Chip Select (often active low, output from master)
SPI Wiring on Raspberry Pi
GPIO 40 pins Connector
[Link]

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
[Link]
MCP3002 ADC chip
The MCP3002 is a 10-bit analog to digital converter with 2 channels (0-1).
The MCP3002 uses a SPI Interface

[Link]
[Link]
raspberry-pi/experiment-3-spi-and-analog-input
Wiring

[Link]
Raspberry Pi GPIO Pins Wiring
+5V (Pin 2)

MOSI GPIO 10 (Pin 19)


MISO GPIO 9 (Pin 21)
SCLK GPIO 11 (Pin 23)
GND(Pin 25)
CS GPIO 8 (Pin 24)
GPIO Zero and MCP3002
gpiozero.MCP3002(channel=0, differential=False, max_voltage=3.3, **spi_args)

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).

[Link]
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

adc = MCP3002(channel=0, differential=True)


1.5V Battery
N = 20
ADC
for x in range(N):
adcdata = [Link] #Value between 0 and 1
#print(adcdata)
voltvalue = adcdata * 5 #Value between 0 and 5V
print(voltvalue)
sleep(1)
[Link]

TMP36
Temperature Sensor

Hans-Petter Halvorsen
TMP36 Temperature Sensor
A Temperature sensor like TM36 use a
solid-state technique to determine the
temperature.

They use the fact as temperature


increases, the voltage across a diode
increases at a known rate.

[Link]
TMP36 Temperature Sensor
Convert form Voltage (V) to degrees Celsius
From the Datasheet we have:

(𝑥! , 𝑦! ) = (0.75𝑉, 25°𝐶)


(𝑥" , 𝑦" ) = (1𝑉, 50°𝐶)

There is a linear relationship between


Voltage and degrees Celsius:
𝑦 = 𝑎𝑥 + 𝑏
This gives:
50 − 25 We can find a and b using the following
𝑦 − 25 = (𝑥 − 0.75)
1 − 0.75 known formula:

Then we get the following formula: 𝑦" − 𝑦!


𝑦 − 𝑦! = (𝑥 − 𝑥! )
𝑦 = 100𝑥 − 50 𝑥" − 𝑥!
Measure Temperature with an ADC
from gpiozero import MCP3002
TMP36 Temperature Sensor from time import sleep

adc = MCP3002(channel=0, differential=False)

N = 10

for x in range(N):
adcdata = [Link] #Value between 0 and 1
#print(adcdata)

Wire a TMP36 temperature voltvalue = adcdata * 5 #Value between 0V and 5V


sensor to the first channel of an #print(voltvalue)
MCP3002 analog to digital tempC = 100*voltvalue-50 #Temperature in Celsius
converter and the other pins to tempc = round(tempC,1)
+5V and GND print(tempC)

sleep(1)
[Link]

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).
• [Link]
• Python Library for ThingSpeak: [Link]
ThingSpeak
ThingSpeak Write
import thingspeak
import time

channel_id = xxxxxx
write_key = "xxxxxxxxxxxxxxxxx"

channel = [Link](id=channel_id, api_key=write_key)

N = 10
for x in range(N):
temperature = 24
response = [Link]({'field1': temperature})
[Link](15)

A Free ThingSpeak Channel can


[Link] only be updated every 15 sec
import thingspeak

Write TMP36 Data


A Free ThingSpeak Channel can
import time
only be updated every 15 sec
from gpiozero import MCP3002

adc = MCP3002(channel=0, differential=False)

channel_id = xxxxxxx
write_key = ”xxxxxxxxxxxxxxxxxx”

channel = [Link](id=channel_id, api_key=write_key)

N = 10
for x in range(N):
#Get Sensor Data
adcdata = [Link] #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 = [Link]({'field1': tempC})
[Link](15)
Write TMP36 Data
Here we see the Temperature Data in ThingSpeak:
ThingSpeak Read
import thingspeak

channel_id = xxxxxx
read_key = ”xxxxxxxxxxxxxxxx"

channel = [Link](id=channel_id, api_key=read_key)

#data = [Link]({})
data = channel.get_field({”field1"})

print(data)

[Link]
Additional Python Resources

[Link]
Hans-Petter Halvorsen
University of South-Eastern Norway
[Link]

E-mail: [Link]@[Link]
Web: [Link]

You might also like