[Link]
blog
Raspberry Pi
with Python
Hans-Petter Halvorsen
Free Textbook with lots of Practical Examples
[Link]
Additional Python Resources
[Link]
Contents
• Overview of Raspberry Pi
• Python on Raspberry Pi
– Using the Thonny Python Editor
• Python
– Basic Python Programming Examples
• Python Libraries/Packages
• GPIO with Examples
Raspberry Pi
Raspberry Pi is a tiny (about 9x6cm), low-cost ($35+),
single-board computer that supports embedded Linux
operating systems
The recommended
Operating System is called
Raspberry Pi OS (Linux
based)
[Link]
Raspberry Pi
GPIO Pins
microSD Card Ethernet
(the Back )
Camera
Connector USB A x 4
Power Supply (USB C) microHDMI x 2
What Do you Need?
• Raspberry Pi
• microSD Card (+ Adapter)
• Power Supply
• microHDMI to HDMI Cable
• Monitor
• Mouse
• Keyboard
Raspberry Pi OS
• In order make your Raspberry Pi up and running you need
to install an Operating System (OS)
• The OS for Raspberry Pi is called “Raspberry Pi OS“
(previously known as Raspbian)
• Raspberry Pi runs a version of an operating system called
Linux (Windows and macOS are other operating systems).
• To install the necessary OS, you need a microSD card
• Then you use the “Raspberry Pi Imager“ in order to
download the OS to the microSD card.
[Link]
Start using Raspberry Pi
• Put the microSD card into the Raspberry Pi
• Connect Monitor, Mouse and Keyboard
Raspberry Pi OS • Connect Power Supply
• Follow the Instructions on Screen to setup Wi-Fi
Remote Access
1. Install XRDP [Link]
– XRDP is a free and open-source implementation of Microsoft RDP
(Remote Desktop Protocol) server. Install it by enter the following:
– sudo apt-get install xrdp
2. Open Remote Desktop Connection (RDC) on
your Windows Computer. RDS is also
available for macOS
– Enter Computer Name or IP Address
– Default UserName is “pi“ and default Password is “raspberry“ (unless
you have changed it)
Python on Raspberry Pi
• The Raspberry Pi OS comes with a
basic Python Editor called ”Thonny“
You can install and use others if you want
[Link]
[Link]
Python Programming
Hans-Petter Halvorsen
Python with Raspberry Pi
• Python is a fairly old Programming Language (1991)
compared to many other Programming Languages
like C# (2000), Swift (2014), Java (1995), PHP (1995).
• Python has during the last 10 years become more and
more popular.
• Today, Python has become one of the most popular
Programming Languages.
• The Raspberry Pi OS comes with a basic Python Editor
called “Thonny“
[Link]
Hello World
Here you also see the
“Thonny“ Python Editor
Free Textbook with lots of Practical Examples
[Link]
Variables in Python
Creating variables: We can use variables in a calculation like this:
> x = 3 > x = 3
> x > y = 3*x
3 > print(y)
We can implement the formula > a = 2
𝑦(𝑥) = 𝑎𝑥 + 𝑏 like this: > b = 4
𝑦(𝑥) = 2𝑥 + 4 > x = 3
> y = a*x + b
> print(y)
A variable can have a short name (like x and y) or a more descriptive name (sum, amount, etc).
You don need to define the variables before you use them (like you need to to in, e.g., C/C++/C).
Calculations in Python
We can use variables in a calculation like this:
𝑦(𝑥) = 2𝑥 + 4
> a = 2
> b = 4
𝑦(3) = ? > x = 3
> y = a*x + b
> print(y)
𝑦(5) = ? > x = 5
> y = a*x + b
> print(y)
Math in Python
If we need only the sin() function, we can do like this: from math import sin
If we need many functions, we can do like this: x = 3.14
y = sin(x)
from math import *
If we need a few functions, we can do like this:
x = pi from math import sin, cos
y = sin(x)
print(y) x = 3.14
y = sin(x) We can also do like this:
y = cos(x) print(y) import math
print(y) x = 3.14
y = cos(x) y = [Link](x)
… print(y) print(y)
If-Else
If you have 2 conditions that you need to check, you can use If – Else:
a = 5
b = 8
if a > b:
print("a is greater than b")
else:
print("b is greater than a or a and b are equal")
Arrays
An array is a special variable, which can hold more than one value at a time
Example:
data = [1.6, 3.4, 5.5, 9.4]
Python does not have built-in support for Arrays, but Python Lists can be used instead.
Length of an Array (List): Get a specific element (Indexing):
N = len(data) x = data[2]
Change a specific element:
Add a new value to the end of the Array (List): data[2] = 7.3
[Link](11.4)
For more advanced use of Arrays in Python you will have to import a library, like the NumPy library.
Using Arrays in Functions
Using Arrays in Functions
Note! statistics is a sub library in the Python Standard Library
Example:
from statistics import *
data = [1.6, 3.4, 5.5, 9.4]
m = mean(data)
sd = stdev(data)
datamin = min(data)
datamax = max(data)
For Loops
A For loop is used for iterating over a sequence. I guess all your programs will use
one or more For loops. So if you have not used For loops before, make sure to learn
it now.
Example:
cars = ["Ford", "Toyota", "Tesla"] Array (List)
of Strings
Note! Python uses for car in cars:
indentation (spaces) print(car)
Other Programming
Languages uses curly Example: data = [1.6, 3.4, 5.5, 9.4] Array (List)
brackets {} or Begin .. End of Numbers
for x in data:
print (x)
For Loops
The range() function is handy to use in For Loops:
N = 10 You can also use the range() function like this:
start = 4
for x in range(N): stop= 12 #but not including
print(x)
The range() function returns a for x in range(start, stop):
sequence of numbers, starting print(x)
from 0 by default, and increments
by 1 (by default), and ends at a
specified number.
Or like this:
While Loops
i = 1 data = [1.6, 3.4, 4.4, 5.5, 9.4]
while i < 10:
print(i) max = 5
i = i + 1
i = 0
1 while data[i] < max:
2 print(data[i])
3 i = i + 1
4
5
6 1.6
7 3.4
8 4.4
9
While Loops
data = [1.6, 3.4, 4.4, 5.5, 9.4]
N = len(data)
sum = 0
24.3
i = 0
while i < N:
sum = sum + data[i]
i = i + 1
print(sum)
Create Functions
Create the Function:
def add(x,y):
z = x + y
return z def add(x,y):
z = x + y
return z
Using the Function within the same script: # Using the Function:
x = 2
y = 5
z = add(x,y)
print(z)
Create Functions
• Although you can mix functions and code in one file, it is much
better to create the functions in separate .py files
• In that way you can easily reuse the function in different Python
scripts
2 Next, we create a new Python File (e.g., “[Link]“)
1 where we use the function we created:
We start by creating a separate from myfunctions import average
Python File, e.g., “[Link]“
for the function: a = 2
[Link]: b = 3
def average(x,y):
c = average(a,b)
return (x + y)/2
print(c)
Free Textbook with lots of Practical Examples
[Link]
Additional Resources
• Python Programming:
[Link]
• Python Programming Tutorial: Getting Started
with the Raspberry Pi
[Link]
getting-started-with-the-raspberry-pi/
[Link]
Python Libraries/
Packages
Hans-Petter Halvorsen
Python Packages/Libraries
• Rather than having all its functionality built into its core,
Python was designed to be highly extensible.
• This approach has advantages and disadvantages.
• A disadvantage is that you need to install these packages
separately and then later import these modules in your code.
• Some important packages are:
– NumPy - NumPy is the fundamental package for scientific
computing with Python
– Matplotlib – With this library you can easily make plots in
Python
Python Packages with Thonny
Tools -> Manage packages…
Installing Python Packages
There are multiple ways to install Python Libraries/ Packages on Raspberry Pi
• apt: Some Python packages can be found in the Raspberry Pi OS archives
and can be installed using apt. Example
sudo apt update
sudo apt install python3-picamera
• pip: Not all Python packages are available in the Raspberry Pi OS archives,
and those that are can sometimes be out-of-date. If you can't find a suitable
version in the Raspberry Pi OS archives, you can install packages from the
Python Package Index (PyPI). To do so, use the pip tool. Example:
sudo pip3 install libraryname
• piwheels: piwheels is a Python package repository specifically for the
Raspberry Pi
[Link]
NumPy
• A Python Library for Numerical
Operations, Arrays, etc.
• The NumPy Python Library is installed
on the Raspberry Pi OS by default
• [Link]
NumPy Example
Basic NumPy Example: In this example we use both the math module in the
import numpy as np Python Standard Library and the NumPy library:
x = 3 import math as mt
import numpy as np
y = [Link](x)
x = 3
print(y)
y = [Link](x)
print(y)
As you see, NumPy also have also similar functions y = [Link](x)
(e.g., sim(), cos(), etc.) as those who is part of the print(y)
math library, but they are more powerful
Matplotlib
• Typically you need to create some plots or charts. In
order to make plots or charts in Python you will need
an external library. The most used library is
Matplotlib
• Matplotlib is a Python 2D plotting library
• Here you find an overview of the Matplotlib library:
[Link]
• The NumPy Python Library is NOT installed on the
Raspberry Pi OS by default, so you must manually
install it
Matplotlib Example
Plotting a Sine Curve
import numpy as np
import [Link] as plt
xstart = 0
xstop = 2*[Link]
step = 0.1
x = [Link](xstart, xstop, step)
y = [Link](x)
[Link](x, y)
[Link]('x')
[Link]('y=sin(x)')
[Link]()
Matplotlib Example
SciPy
• SciPy has many functions for
Mathematics and Scientific
Computing
• [Link]
• [Link]
rence/
Install SciPy with Thonny
[Link]
Python from
Command Line
Hans-Petter Halvorsen
Python from Command Line
• You can write a Python file in a standard editor
• Then you run it as a Python script from the
command line.
• Just navigate to the directory where the file is
saved in (use commands cd and ls for navigation)
python3 [Link]
Python from Command Line
Python Shell from Terminal
Enter python3 in the Terminal
[Link]
GPIO
Hans-Petter Halvorsen
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
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
[Link]
GPIO with Python
Hans-Petter Halvorsen
Raspberry Pi GPIO and Python
• You can make all kinds of Python program on your Raspberry Pi
• But you could have used your ordinary desktop/laptop PC for
that
• The UNIQUE thing with Raspberry Pi compared to an ordinary
PC is the GPIO connector
• With GPIO you can connect LEDs, Sensors, control Motors, etc.
• You typically use Python in order communicate with GPIO
connector
• That what's makes the combination Raspberry Pi + Python
UNIQUE!
GPIO in Python
• In order to use and communicate
with the GPIO Pins we typically use
the Python Programming Language
• We can turn on LEDS, read data from
different types of Sensors, etc.
[Link]
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]
Necessary Equipment
• Raspberry Pi
• Breadboard
• LEDs
• Push Buttons
• Resistors
• Wires (Jumper Wires)
Breadboard
A breadboard is used to wire
electric components together
Resistors
Resistance is measured in Ohm (Ω)
Resistors comes in many sizes, e.g., 220Ω , 270Ω,
330Ω, 1kΩm 10kΩ, ...
The resistance can be found using Ohms Law
𝑈 = 𝑅𝐼
[Link] Electrical symbol:
Resistor Colors
You can also use a Multimeter
Resistor Calculator: [Link]
[Link]
LED
Hans-Petter Halvorsen
Necessary Equipment
• Raspberry Pi
• Breadboard
• LED
• Resistor, 𝑅 = 270Ω
• Wires (Jumper Wires)
Setup and Wiring
LED
[Wikipedia]
Breadboard Wiring
Make sure not to short-circuit
the components that you
wire on the breadboard
Raspberry Pi GPIO Pins
LED Example
LED
R=270Ω
GND (Pin 32)
GPIO16 (Pin 36)
Breadboard
Why do you need a Resistor?
If the current becomes too large, the LED will be destroyed. To prevent
this to happen, we will use a Resistor to limit the amount of current in
the circuit.
What should be the size of the Resistor?
A LED typically need a current like 20mA (can be found in the LED Datasheet).
We use Ohm’s Law:
𝑈 = 𝑅𝐼
Arduino gives U=5V and I=20mA. We then get:
𝑈
𝑅=
𝐼
!"
The Resistor needed will be 𝑅 = #.#%& = 250Ω. Resistors with R=250Ω is not so common, so
we can use the closest Resistors we have, e.g., 270Ω
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)
Additional Python Resources
[Link]
Hans-Petter Halvorsen
University of South-Eastern Norway
[Link]
E-mail: [Link]@[Link]
Web: [Link]