50
Programming Python on the Raspberry Pi Michael Weigend Universität Münster Holzkamp-Gesamtschule Witten Vilnius 2014

Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

  • Upload
    others

  • View
    53

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Programming

Python

on the Raspberry Pi

Michael Weigend

Universität Münster

Holzkamp-Gesamtschule Witten

Vilnius 2014

Page 2: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Outline

Presentation 1 “Introduction to Python” (30 min)

Application domains, basic features, functions, data structures, OOP, logical correctness

(assertions)

Hands On Exercise 1 (60 min)

Presentation 2 “Raspberry Pi and Python Projects in the Classroom”

(30 min)

Python Projects in the Classroom (XP), Python on the Raspberry Pi

Coffee Break

Hands on Exercise 2 (50 min) advanced tasks: GUI programming and programming the Raspberry Pi

Final discussion (10 min)

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 3: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Application Domains

Page 4: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Created With Python

Creator: Stani Michiels

Page 5: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

A Minimalist Version

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 6: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

20 Lines of Code

Page 7: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Visualization of the Mandelbrot Set from tkinter import *

RADIUS = 2.0

ZOOM = 50.0

class Mandelbrot:

def __init__(self):

self.window = Tk()

self.image = PhotoImage(width=200, height=200)

self.image_label = Label(master=self.window,

image=self.image)

self.image_label.pack()

self.draw()

self.window.mainloop()

def draw(self):

interval = [x/ZOOM for x in range(-100, 100)]

mandelbrot = [(x, y) for x in interval

for y in interval

if self.test(x, y)]

for x, y in mandelbrot:

self.image.put("#0000ff", (int(ZOOM*x+100), int(ZOOM*y+100)))

def test (self, x, y):

c = x + 1j * y # j is the imaginary number i

z = 0

for i in range(20):

if abs (z)< RADIUS:

z = z*z - c

else: return False # not in the Mandelbrot set

return True # element of the Mandelbrot set

m = Mandelbrot()

Page 8: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Image Processing and Steganographie

# stegano.pyw

from tkinter import *

class App:

def __init__(self):

self.filename="manchester_6.ppm"

self.window = Tk()

self.pic = PhotoImage(file= self.filename)

self.c = Canvas(self.window, width=self.pic.width(),

height=self.pic.height())

self.c.pack()

self.c.create_image(0, 0, anchor=NW, image=self.pic)

self.ExtractButton = Button(master=self.window,

text="Find Words",

command=self.extract)

self.ExtractButton.pack()

self.window.mainloop()

def extract(self):

w = self.pic.width()

h = self.pic.height()

colors = [self.pic.get(i,0) for i in [0, 1, 2, 3]]

pixels = [(x, y) for x in range(w) for y in range(h)]

for (x, y) in pixels:

if self.pic.get(x, y) not in colors:

self.pic.put("white", to=(x, y))

else:

self.pic.put("{black black} {black black}", to=(x, y))

App() App()

Page 9: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Application Domains

• creative projects Disney VR Studio, Industrial Light & Magic

• science American Space Telescope Institute, Deutsche Gesellschaft für Luft- und Raumfahrt

• web services Google, BSCW, Dropbox

• security sensible systems governments, airlines, banking

• Education universities (MIT), schools

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 10: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Advantages of Python

• simple (minimalist)

• consistent

• short programs

• platform independent

• open source

• many programming paradigms

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 11: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Computer Programs

are Written for Humans

Donald Knuth (1984):

„I believe that the time is ripe for

significantly better documentation of

programs, and that we can best

achieve this by considering

programs to be works of

literature.”

Knuth, D. E.: Literate Programming. In:

The Computer Journal 27/2, 1984, S.

97-111.

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 12: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Dynamic Typing

int a;

double[3] s;

a = 3;

s = [1.1, 2, 3]

a = 3

s = [1.1, 2, 3]

Python Java

Name

Type

Object

int

float Ducktyping

Name

Type Object

Page 13: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Intuitive Models

Python Java

int a;

a = 3;

a = 3;

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 14: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Verbosity: Minimal Code

if ( a > b )

{

a = b;

b = c;

}

if a > b:

a = b

b = c

no semicolons

indentation for defining blocks of code

Python Java

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 15: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Associated Boolean Values

None () {} [] 0 False

s = [1, 3, 5]

while s:

print s[0]

del s[0]

1

3

5

“Empty “ objects

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 16: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Using Common Mathematical Notation

if((14 < age) && (age < 60))

{

System.out.println("Welcome!")

}

if 14 < age < 60:

print ("Welcome!")

which program text is easier to

understand?

Python Java

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 17: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

(Implicit) Tuples

a, b = 12, 14

a, b = b, a

Simple swapping

Compact assignments

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 18: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Functions

Live Presentation 1

• position parameters

• keyword parameters

• docstring

• default values and multiple number of parameters

def area (…)

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 19: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Type

Hierarchy

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 20: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Operations for Collections

>>> numbers = [2, 3, 56, 12]

>>> 1 in numbers

False

>>> "e" in "Delft"

True

in

>>> for c in "Delft" : print (c)

D

e

l

f

t

>>> for i in numbers:

print (i)

2

3

56

12

Iteration

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 21: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Operations for Sequences

concatenation

indexing and slicing

>>> w = "Delft"

>>> 'Tiles from ' + w

'Tiles from Delft'

>>> 2*w

'DelftDelft'

>>> w[0]

'D'

>>> w[0:2]

'De'

>>>

>>> w[2:]

'lft'

>>> numbers = [2, 3, 56, 12]

>>> 2*numbers

[2, 3, 56, 12, 2, 3, 56, 12]

>>> numbers = [2, 3, 56, 12]

>>> numbers[0]

2

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 22: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

List mutable sequence

list items may be all kinds of objects

[1, 2, 3]

[1, "a", [1, 2], len]

[]

[[], [], []]

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 23: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

List Comprehension

[n*n for n in [1, 2, 3]]

Which items are in this list?

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 24: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

List Comprehension

[n*n for n in [1, 2, 3]]

[1, 4, 9]

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 25: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Set Builder Notation

s = {2*x for x in {1, 2, 3, 4, 5} if x**2 > 3}

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 26: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Modeling with Lists

Stack last in – first out

>>> stack = [3, 4, 5]

>>> stack.append(6)

>>> stack.append(7)

>>> stack

[3, 4, 5, 6, 7]

>>> stack.pop()

7

>>> stack

[3, 4, 5, 6]

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 27: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Modeling with Dictionaries

Mapping key value

>>> tel = {'jack': 4098, 'tom': 4139}

>>> tel['guido'] = 4127

>>> tel

{‘tom': 4139, 'guido': 4127, 'jack': 4098}

>>> tel['jack']

4098

>>> del tel[‘tome']

>>> tel

{'guido': 4127, 'jack': 4098}

create a dictionary

find a value using a key

delete an item

add an item

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 28: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Object Oriented Programming

Everything is an object!

>>> a=1

>>> type(a)

<class 'int'>

>>> id(a)

9786792

>>> a + 2

3

>>> a.__add__(2)

3

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 29: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Object Oriented Programming

Live Presentation 2

• Class definition

• Class attributes, object attributes

• Methods

• Polymorphism (overloading)

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 30: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Modeling Volume

0.05 mL

1.0 L

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 31: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

How to find a bug?

Complex program

Simple

condition

Simple

condition

Simple

condition

Page 32: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Quicksort

def qsort (sequence):

s = sequence[:] # s is a copy of sequence

if s == []:

result = s # end of recursion

else:

x = s[0] # take first element

del s[0]

s1 = [] # split remaining list

s2 = []

for i in s:

if i <= x:

s1.append(i)

else:

s2.append(i)

result = qsort(s1) + [x] + qsort(s2) # recursive calls

return result

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 33: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Quicksort checking postconditions

def qsort (sequence):

s = sequence[:] # s is a copy of sequence

if s == []:

result = s # end of recursion

else:

x = s[0] # take first element

del s[0]

s1 = [] # split remaining list

s2 = []

for i in s:

if i <= x:

s1.append(i)

else:

s2.append(i)

result = qsort(s1) + [x] + qsort(s2) # recursive calls

assert len(result) == len (sequence)

return result

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 34: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Hands-on Exercise 1

Presentation 1 “Introduction to Python” (30 min)

Application domains, basic features, functions, data structures, OOP, logical correctness

(assertions)

Hands On Exercise 1 (60 min)

Presentation 2 “Raspberry Pi and Python Projects in the Classroom”

(30 min)

Python Projects in the Classroom (XP), Python on the Raspberry Pi

Coffee Break

Hands on Exercise 2 (50 min) advanced tasks: GUI programming and programming the Raspberry Pi

Final discussion (10 min)

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 35: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Part 2

Python Projects in the

Classroom –

Raspberry Pi Projects

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 36: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Agile Classroom Projects Extreme Programming (Kent Beck)

Invent a project metaphor

write stories

Start with an architectural spike solution

Implement stories in short iterations

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 37: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

User can choose a font

Stories

User can insert phrases ( “Dear friend!”)

The Letter Fairy

A text editor that helps young children writing

letters in a foreign language.

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 38: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Start with an Architectural Spike

from tkinter import *

class Editor:

def __init__ (self):

# widgets

self.window = Tk()

self.window.title("Text Editor 1")

self.text = Text(master=self.window)

self.text.pack()

# window

self.window.mainloop()

Editor()

9 lines of code

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 39: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

At the End of the First Iteration ----------------------------------------------------

# file name: editor3.pyw

# A simple text editor with menu for open and save

# Michael Weigend 2009

#----------------------------------------------------

from tkinter import *

class Editor:

def __init__ (self):

# Textfeld

self.window = Tk()

self.text= Text(master=self.window,

wrap=WORD, font=('Arial', 10))

self.text.pack()

# Menu Bar

self.menuBar=Menu(master=self.window)

self.window.config(menu=self.menuBar)

# file menu

self.fileMenu=Menu(self.menuBar)

self.fileMenu.add_command(label="Open",

command = self.load)

self.fileMenu.add_command(label="Save as",

command = self.save)

self.fileMenu.add_separator()

self.fileMenu.add_command(label='Quit',

command=self.quit)

self.menuBar.add_cascade(label="file",

menu=self.fileMenu)

self.window.mainloop()

# methods

def load (self):

self.file = filedialog.askopenfile()

self.text.delete(1.0, END) # delete all text in text area

if self.file:

self.text.insert(1.0, self.file.read()) # read text from file and insert it

def save (self):

self.file = filedialog.asksaveasfile()

if self.file:

self.file.write(self.text.get(1.0, END) )

self.file.close()

def quit(self):

if messagebox.askyesno('Finish',

'Do you really want to quit?'):

self.window.destroy()

Editor()

approx. 50 lines of code

Page 40: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Programming the Raspberry Pi

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 41: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Computer = Black Box

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 42: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Open The Black Box

Page 43: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Mail From All Over The World

Michael Weigend: Programming

Python on the Raspberry Pi, Vilnius

2014

Page 44: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Project: Collecting and Processing

Temperature Data

analog

digital

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 45: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Direct-to-Digital

Sensor

physical

phenomenon

Computer

data package

Information

temperature-

sensitive oscillator

DS1820

1-Wire-Bus

ID

temperature

(-55 to +125 °C)

temperature crc

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 46: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Hardware Configuration

GPIO

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 47: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Wiring Diagram

R=4,7kΩ …

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 48: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Reading data with modprobe

sudo modprobe wire

sudo modprobe w1-gpio

sudo modprobe w1-therm

Temperature

information

ID of the sensor

28 = DS18B20

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 49: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Temperature Data Logger os.system("modprobe wire")

os.system("modprobe w1-gpio")

os.system("modprobe w1-therm")

for d in os.listdir("/sys/bus/w1/devices"):

if d.startswith("10") or d.startswith("28"):

deviceFile = "/sys/bus/w1/devices/" + d + "/w1_slave"

def readTemp():

ok = False

while not ok:

f = open(deviceFile, "r")

firstLine, secondLine = f.readlines()

f.close()

if firstLine.find("YES") != -1:

ok = True

tempString = secondLine.split("=")[1]

return int(tempString)/1000

while True:

print(readTemp())

time.sleep(1)

Output: 22.937

22.312

22.312

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014

Page 50: Programming Python on the Raspberry Pi · Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014 . Application Domains. Created With Python Creator: Stani Michiels

Hands-on Exercise 2

Presentation 1 “Introduction to Python” (30 min)

Application domains, basic features, functions, data structures, OOP, logical correctness

(assertions)

Hands On Exercise 1 (60 min)

Presentation 2 “Raspberry Pi and Python Projects in the Classroom”

(30 min)

Python Projects in the Classroom (XP), Python on the Raspberry Pi

Coffee Break

Hands on Exercise 2 (50 min) advanced tasks: GUI programming and programming the Raspberry Pi

Final discussion (10 min)

Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014