Programming Python on the Raspberry Pi

Transcription

Programming Python on the Raspberry Pi
Programming
Python
on the Raspberry Pi
Michael Weigend
Universität Münster
Holzkamp-Gesamtschule Witten
Vilnius 2014
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
Application Domains
Created With Python
Creator: Stani Michiels
A Minimalist Version
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
20 Lines of Code
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()
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()
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
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
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
Dynamic Typing
Python
int
a = 3
s = [1.1, 2, 3]
Ducktyping
float
Java
int a;
double[3] s;
a = 3;
s = [1.1, 2, 3]
Name
Object
Type
Name
Object
Type
Intuitive Models
Python
Java
int a;
a = 3;
a = 3;
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Verbosity: Minimal Code
Python
Java
if a > b:
a = b
b = c
if ( a > b )
{
a = b;
b = c;
}
no semicolons
indentation for defining blocks of code
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Associated Boolean Values
None () {} [] 0
False
“Empty “ objects
s = [1, 3, 5]
while s:
print s[0]
del s[0]
1
3
5
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Using Common Mathematical Notation
Python
if 14 < age < 60:
print ("Welcome!")
Java
if((14 < age) && (age < 60))
{
System.out.println("Welcome!")
}
which program text is easier to
understand?
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
(Implicit) Tuples
a, b = 12, 14
Compact assignments
a, b = b, a
Simple swapping
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
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
Type
Hierarchy
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Operations for Collections
in
>>> "e" in "Delft"
True
>>> numbers = [2, 3, 56, 12]
>>> 1 in numbers
False
Iteration
>>> for c in "Delft" :
print (c)
>>> for i in numbers:
print (i)
D
e
l
f
t
2
3
56
12
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Operations for Sequences
concatenation
>>> w = "Delft"
>>> 'Tiles from ' + w
'Tiles from Delft'
>>> 2*w
'DelftDelft'
>>> numbers = [2, 3, 56, 12]
>>> 2*numbers
[2, 3, 56, 12, 2, 3, 56, 12]
indexing and slicing
>>> w[0]
'D'
>>> w[0:2]
'De'
>>>
>>> w[2:]
'lft'
>>> numbers = [2, 3, 56, 12]
>>> numbers[0]
2
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
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
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
List Comprehension
[n*n for n in [1, 2, 3]]
[1, 4, 9]
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
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
Modeling with Lists
Stack
last in – first out
>>>
>>>
>>>
>>>
[3,
>>>
7
>>>
[3,
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
4, 5, 6, 7]
stack.pop()
stack
4, 5, 6]
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Modeling with Dictionaries
Mapping key  value
create a dictionary
>>> tel = {'jack': 4098, 'tom': 4139}
add an item
>>> tel['guido'] = 4127
>>> tel
{‘tom': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel[‘tome']
>>> tel
{'guido': 4127, 'jack': 4098}
find a value using a key
delete an item
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
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
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
Modeling Volume
1.0 L
0.05 mL
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
How to find a bug?
Simple
condition
Complex program
Simple
condition
Simple
condition
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
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
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
Part 2
Python Projects in the
Classroom –
Raspberry Pi Projects
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
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
The Letter Fairy
A text editor that helps young children writing
letters in a foreign language.
Stories
User can insert phrases ( “Dear friend!”)
User can choose a font
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
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
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
approx. 50 lines of code
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()
Programming the Raspberry Pi
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Computer = Black Box
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Open The Black Box
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Mail From All Over The World
Michael Weigend: Programming
Python on the Raspberry Pi, Vilnius
Project: Collecting and Processing
Temperature Data
digital
analog
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Direct-to-Digital
physical
phenomenon
Information
data package
ID
temperature
Sensor
temperature
(-55 to +125 °C)
crc
Computer
1-Wire-Bus
temperaturesensitive oscillator
DS1820
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Hardware Configuration
GPIO
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Wiring Diagram
…
R=4,7kΩ
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Reading data with modprobe
ID of the sensor
28 = DS18B20
sudo modprobe wire
sudo modprobe w1-gpio
sudo modprobe w1-therm
Temperature
information
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
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)
Michael Weigend: Programming Python on the Raspberry Pi, Vilnius 2014
Output:
22.937
22.312
22.312
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

Similar documents