[Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi

Week 1

Reading Material

Lesson 1

Lecture 1.1 Raspberry Pi Board

Raspberry Pi Hardware Specs
  • Broadcom BCM2836 SoC
    • 900Mhz, 1Gb RAM
  • Dual Core VideoCore IV Multimedia Co-Processor
    • GPU
  • 40 GPIO pis
    • only 26 on Raspberry Pi A and B
  • 4 USB ports
    • only 2 on the Raspberry Pi B
  • Micro SD card slot
    • full-sized SD card slot on previous Raspberry Pi
Raspberry Pi B+
[Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi_第1张图片
IoTM4W1L1.1.png
[Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi_第2张图片
IoTM4W1L1.1_2.png

Lecture 1.2 Raspberry Pi Processor

ARM Processors
  • ARM licenses : Intellectual property
  • Silicon vendors build System-on-Chip(SoC) designs using ARM IP
  • 15+ silicon vendors use ARM
ARM Processor Family
  • Broadcom BCM2836 SoC is ARM Cortex A7

Lecture 1.3 Raspberry Pi vs. Arduino

Raspberry Pi vs. Arduino
  • Raspberry Pi processor is faster
    • 900MHz vs 16MHz
  • 32-bit processor vs. 8-bit
    • Bigger address space, number representations
  • Raspberry Pi has more memory
    • Arduino: 32K Flash, 2K SRAM, 1K EEPROM
    • Raspberry Pi: 512K SRAM, 4G Flash, micro SD
  • Raspberry Pi has lower I/O voltage levels
    • 3.3V vs. 5V
Using an Operating System
  • Raspberry Pi can support an operating system
  • Enables a range of features

Lesson 2

Lecture 2.1 Operating System Benefits

User Interface
  • Text-based interface : Type commands directly into text-based console
  • Graphic interface : Use point-and-click interface
File System
  • Can create and modify files in a directory structure
  • Similar to other file system interfaces

Lecture 2.2 Processes

Multiple Processes
  • Can download and run multiple programs
  • Can execute many processes concurrently
Using Hardware Devices
  • User Application : Any application running in user space
  • /dev/xxx : File associated with a hardware device
  • Device Driver : Concert file accesses t device accesses; enable apps to access arbitrary hardware devices
  • HW device : keyboard, monitor, etc.

Lecture 2.3 Raspberry Pi IoT

Is Raspberry Pi and IoT Device?

Maybe - Depends on how it is used
Similarities

  • Network connectivity and computational intelligence
  • Small and cheap (relative to a PC)
  • Can interface directly with sensors/actuators via pins

Differences

  • Interface can be exactly the same as PC running Linux
    • Complexities of the system can be visible

Lesson 3

Lecture 3.1 Raspberry Pi Setup

Setup of the Raspberry Pi

Step1 : Plug in a monitor(via HDMI) and a keyboard and mouse (via USB)

  • Need an interface to the device

Step2 : Get an operating system

  • Raspberry Pi needs an operating system
  • Operating system image must be present on the micro SD card
Installing an Operating System

use New Out-Of-Box Software(NOOBS)

  • Comes preinstalled on micro SD bundled with Raspberry Pi boards
  • Otherwise, download it for free from www.raspberrypi.org/downloads
  • If NOOBS is not preinstalled on micro SD, you'll need to:
    1. Format the micro SD (need an SD reader)
    2. Extract the NOOBS downloaded
    3. Put it on the micro SD
NOOBS
  • NOOBS will install an operating system on your micro SD card
  • You get a choice of the OS
    • Short list if you have no network access; long list otherwise
  • Choose Raspian (a Linux distribution), the default option

Lecture 3.2 Raspberry Pi Configuration

Raspi-Config
  • raspi-config is a tool which lets you setup various setup/boot options for the Raspberry Pi
  • raspi-config will run automatically when you boot the Raspberry Pi with a new micro SD card for the first time
Raspi-Config Options
  • Expand Filesystem - Reformats your micro SD card filesystem to allow access to all the memory
  • Change User Password - Raspberry Pi starts with one user account(username: "pi") with a default password ("raspberry")
  • Enable Boot to Desktop/Scratch
    • Console is default boot option
    • Desktop is the graphic interface
    • Scratch is a programming environment for kids
    • Desktop may not be necessary
  • Internationalisation and Rastrack
    • Internationalisation Options
      • Change Locale - Select a language
      • Change Timezone
      • Change Keyboard Layout
        • QWERTY is default
    • Add to Rastrack
      • Service that allows Raspberry Pi users to find one another
      • Totally optional
      • Approximate location based on IP address

Lecture 3.3 Overclocking

Overclocking
  • Overclocking refers to increasing the clock frequency of the device, beyond the recommended frequency
  • Overclocking may also refer to increasing the internal voltage levels to increase speed
  • There are several different clocks inside a typical device
    • ARM frequency: clock driving the ARM processor core
    • SDRAM frequency: clock driving memory
Impact of Overclocking
  • Instructions are executed more quickly
    • Roughly one instruction per clock period
  • Signals have shorter time in which to travel
    • Signals must travel between storage elements in a single clock period
    • signal data may not reach destination in time
  • Temperature of device increases
    • Shortens device lifetime
Impact of Increasing Voltage
  • Increased voltage swing may increase transistor speed
  • Power consumption in proportional to V²
  • Thermal effects may alter timing

Week 2

Reading material

Lesson 1

Lecture 1.1 Linux Basics

The Shell
  • Interprets user input and executes commands
  • Text-based user interface of an operation system
  • bash (bourne again shell) is the default shell for Raspian
  • Gives more precise control to the user
  • Requires memorization for efficiency
Console or Terminal
  • The console or terminal is a text entry and display device
    • Used to be a physical device (vt100 terminal)
    • Virtual consoles are typical now
  • LXTerminal is the terminal used in Raspian

Lecture 1.2 Login

Accounts
  • There can be many user accounts on a Linux system
  • Each account has a username and password for identification
  • When you first start the machine, you are prompted for username and password
  • Default username is "pi", password is "raspberry"
Man(ual) Pages
  • "man" give information about a Linux command

Lecture 1.3 Linux Filesystem

The Filesystem
[Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi_第3张图片
IoTM4W2L1.3.png
  • Hierarchy of directories and files
PWD

Lesson 2

Lecture 2.1 Navigating the Filesystem

CD
  • To a specific directory
  • Up or down one level
ls
  • Show the contents of a directory
    • Files and other directories
  • -l option shows all detail
Mkdir, Rmdir
  • mkdir creates a directory
  • rmdir removes a directory
  • rmdir only works if directory is empty

Lecture 2.2 Text Editors

Creating Files
  • Many ways to do this, depending on the type of file you want to create
  • Typical method involves a text editor
    • Like a word processor but simpler
  • Several are available on Linux for free
    • Emacs, vi, vim, etc.
  • Choose a favorite and stick with it
Nano
  • Run it by typing "Nano" at the prompt
  • Basic functions via control sequence

Lecture 2.3 Accessing Files

Viewing a File
  • "cat" prints the file to the terminal
  • "head" prints the first 10 lines
  • "last" prints the last 10 lines
CP
  • Make a copy of a file
MV
  • Move a file
  • Rename it or move it to a new directory

Lesson 3

Lecture 3.1 Permissions

File Permissions
  • Files have owners
    • User who created the file
  • Files have access permissions
    • Read (r), write(w), execute(x)
  • Different permissions can be assigned according to type
    1. User: the file owner
    2. Group: a permission group
    3. Other: all users
Viewing File Permissions
Root Account
  • THe root account has highest permission level
  • Key files and directories are only accessible by root
  • Sometimes you need root privileges
    • Install a program
    • Change the operating system
  • Use the "sudo" command to gain root permission for a single command

Lecture 3.2 Processes

Processes
  • A process is the execution of a program
  • Linux allows multiple processes to run concurrently
    • Foreground vs. background
  • User can do something while other tasks are taken care of
    • Read email
    • Download file
    • Wait for network connection
    • check for viruses
Viewing Processes
  • Each process has a unique PID
  • "kill" can be used to end a process
Shutdown
  • Should not just unplug a Linux machine
  • Proper shutdown procedure is needed to place data structures in a good state
    • Flush all buffers, close files, etc.
  • Use the "shutdown" command

Lecture 3.3 Linux Graphic User Interface

Using the GUI for Raspian
  • After initial login, type "startx"
  • Initiates the X Windows system with a default window manager
  • The manager determines the look
File Manager
  • Allows easy file access

Week 3

Reading Material

Lesson 1

Lecture 1.1 Python on Raspberry Pi

Raspberry Pi for IoT
  • Raspberry Pi can be used as a laptop/desktop
  • To use it as part of an IoT device, programming is needed
  • Many languages can be used
    • Need a compiler (C, C++, Java, etc.) and an interpreter (Java, Python, Perl, tec.)
  • Python is most convenient
    • Good programming environment built-in
    • Good APIs available to access Raspberry Pi hardware
Python Language
  • High-level language, easy to use
    • Do not need to explicitly declare data types
    • No pointers
    • Object-oriented programming, classes
  • Slow compared to C, C++
    • Interpreted, not compiled
  • Two versions: Python 2.x and Python 3.x
    • Python 2.x is still supported
    • Programming differences are small
    • Will use Python 3.x

Lecture 1.2 Python Programming Environment

Python Programming Environment

Two possible environments:

  1. Integrated Development Environment(IDE)

    • IDLE is the best option
    • Invoke via Menu > Programming > Python
    • Select Python 2 or Python 3 (use 3 for now)
  2. Text editor and interpreter, separately

    • Use Pico or Nano to write a program, "test.py"
    • Execute program by typing "python3 test.py"
Executing Python Code

Two ways to do it:

  1. Interactive: execute lines typed interactively in a Python console.
  2. Batch: execute an entire Python program
    • Interactive execution requires a Python shell
      • Start IDLE, shell s default
      • In terminal, type "python3"
Executing Programs from IDLE
  1. Start IDLE
  2. File > New File to create a new text editor window
  3. Type in code
  4. Select Run > Run Module
  5. Python shell will open and code will execute

Lecture 1.3 Python Expressions

Algebraic Expressions
  • Python shell can evaluate algebraic expressions
  • Many algebraic expressions
    • abs()
    • min()
    • max()
Boolean Expressions
  • Evaluate to True or False
  • Often involve comparison operators <, >, ==, !=, <=, and >=
Boolean Operators
  • Evaluate to True or False
  • May include Boolean operators and, or, not
Variables, Assignments
  • Variable types are not declared
  • Interpreter determines type by usage

Lesson 2

Lecture 2.1 Strings

Strings
  • A sequence of characters enclosed in quotes 'Hello, world'
  • Can be assigned to a variable
  • Can be manipulated using string operators and functions
String Operators
[Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi_第4张图片
IoTM4W3L2.1.png
Indexing Operator
  • Index of an item in a sequence is its position in the sequence
  • Indexing operator is [], takes an index as argument
  • Indices start at 0
  • Can be used to identify characters in a string

Lecture 2.2 Functions

Defining Functions
  • A sequence of instructions associated with a function name
  • Function definition starts with def
  • Followed by function name, open/close parentheses, and colon
>>> def test():
     print('A test function')

>>> test()
A test function
>>>
Defining/Calling Functions
  • All instructions in a function definition are indented
    • IDLE does this automatically
  • Function is called by typing function name with parentheses after it

Lecture 2.3 Function Arguments

Function Parameters/Arguments
  • A function can take arguments which are values bound to variables inside the function
  • Argument are listed between parenthesis in the function call
>>> def circle_area(rad) :
      print(3.14 * rad * rad)
>>> circle_area(2)
12.56
Function Return Values
  • Functions can return values with the return instruction
  • A function call is substituted for its return value in an expression
>>> def circle_area(rad) :
      return 3.14 * rad * rad
>>> circle_area(2)
12.56
>>> 3 + circle_area(2)
15.56
>>>

Lesson 3

Lecture 3.1 Lists

Lists
  • A comma-separated sequence of items in square brackets
  • Items can be numbers, strings, other lists, etc.
>>> pets = ['ant', 'bat', 'cod', 'dog']
>>> lst = [0, 1, 'two', [4, 'five']]
>>> nums = [0, 1, 2, 3, 4]
>>>
List Operators and Functions
[Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi_第5张图片
IoTM4W3L3.1.png

Lecture 3.2 Lists Methods

List Methods
  • List operators that are called on the list that they operate on
>>> lst = [1, 2, 3]
>>> lst.append(8)
>>> lst
[1, 2, 3, 8]
[Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi_第6张图片
IoTM4W3L3.2.png
  • append(), remove(), reverse(), and sort() do not return values
  • They only modifier the list

Lecture 3.3 Control Flow

Control Flow

Statements that change the order in which lines or code are executed

  1. if statement
  2. for loop
  3. while loop
If statement

Template:

if :
    

Example:

if temp > 80:
    print('It is hot!')
print('Goodbye.')
If-else statement

Template:

if :
    
else:
    

Example:

if temp > 80:
    print('hot!')
else:
    print('not hot.')
print('Goodbye.')
For Loop
  • Executes a block of code for every element in a sequence
  • Variable is bound to a sequence element on each pass
>>> name = 'Ian'
>>> for char in name:
     print(char)
I
a
n
>>>
For Example
  • Any sequence can be used
  • All code in loop must be indented
>>> for name in ['Jon', 'Mary', 'Pete']:
     print(name)
Jon
Mary
Pete
>>>
While Loop
  • Execute indented block of code while condition is True
>>> i = 0
>>> while i < 3:
     print(i)
     i = i + 1
0
1
2
>>>

Week 4

Reading material

Lesson 1

Lecture 1.1 General Purpose IO Pins

GPIO Pins Raspberry Pi B+
[Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi_第7张图片
IoTM4W4L1.1.png
  • Dedicated power and ground pins
  • 3.3V(1,17), 5V(2,4),Gnd(6,9,14,20,30,39)
General Purpose/Multi-Function
  • Pins labeled "GPIOxx" can be used as general purpose I/O
  • Some pins are multi-function
    • Extra label
UART Pins
  • Pins 8 and 10 can be used for UART(serial) communication
  • TX for transmission
  • RX for receiving

Lecture 1.2 Protocol Pins

I2C Pins
  • Pins 3 and 5 can be used for I2C communication
  • SDA for data
  • SCL for clock
SPI Communication Pins
  • MOSI(19), MISO(21), SCLK(23)
  • 2 pins for chip enable, CE0(24) and CE1(26)

Lecture 1.3 GPIO Access

GPIO Access in Python
  • Use the GPIO library
  • import Rpi.GPIO as GPIO
  • Execute your Python program (script) as root
    • Use "sudo" for this
Pin Numbering Modes

Two ways to refer to the pins

  1. The number of the pins in their order on the board
    • Shown in circles in the picture
  2. The Broadcom SoC number
    • Shown in rectangles, after "GPIO"
Selection Pin Numbering Mode

GPIO.setmode(GPIO.BOARD)

  • Use board numbering

GPIO.setmode(GPIO.BCM)

  • Use Broadcom SoC numbering
  • Changes with different versions of Raspberry Pi

Lesson 2

Lecture 2.1 General Purpose IO Pins

Pin Direction and Assignment

GPIO.setup(13, GPIO.OUT)

  • Set the pin direction
  • Like pinMode(13,OUTPUT) for Arduino

GPIO.setup(13, GPIO.OUT)

  • Assign value to output pin
  • Like digitalWrite(11,HIGH) for Arduino
Blink an LED
import Rpi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.OUT)
while True:
    GPIO.output(13, True)
    time.sleep(1)
    GPIO.output(13, False)
    time.sleep(1)
Reading Input Pins

GPIO.setup(13, GPIO.IN)

  • Set the pin direction to an input

value = GPIO.input(13)

  • Read value on input pin
  • Only reads digital inputs
    • No analogRead equivalent
    • No analog-to-digital converter

Lecture 2.2 Pulse Width Modulation

Pulse Width Modulation

PWM functions in GPIO library

PWM Initialization

pwm_obj = GPIO.PWM(18, 400)

  • Mark pin for PWM
  • Second argument is frequency

pwm_obj.start(100)

  • Start generating PWM signal
  • Argument is duty cycle, 0 to 100
PWM Control

pwm_obj.ChangeDutyCycle(50)

  • Assign new duty cycle
  • PWM frequency is not accurate
    • Off by over 50% at 10 kHz
Frequency Control
  • Cannot easily control frequency
    • No tone() function as on Arduino
  • Need to do it manually
While True:
    GPIO.output(18, True)
    time.sleep(0.5)
    GPIO.output(18, False)
    time.sleep(0.5)
  • 1Hz frequency

Lecture 2.3 Demo of a Blink

Lesson 3

Lecture 3.1 Graphic User Interface

Graphic User Interface
  • Can use a GUI to access the GPIO
  • Raspberry Pi does it ... Arduino doesn't
    • GUIs are supported by the operating system
  • Various visual entities (widgets) you can interact with
    • Buttons, menus, sliders, scrollbars
    • Drawing surfaces for drawing
  • Execution is controlled by the user, not the programmer
    • File opened when "open" button is clicked
Event Loop
  • Typically, program will wait for the user to activate one of its widgets
    • Push a button, select a menu item, draw on a drawing surface etc.
  • Do something in response
  • Then wait for you to do something else

Lecture 3.2 Tkinter Library

Tkinter
  • Tkinter library provides tools for writing programs that use graphics:
    • many GUI widgets
      • buttons, menus, labels, scrollbars, etc.
    • a canvas widget on which arbitrary drawing can be created
      • using lines, circles, rectangles, ovals, images, text, etc.
from Tkinter import *
root = Tk()
root.geometry('800x600')
c = Canvas(root, width=800, height=600)
c.pack()
r = c.create_rectangle(0, 0, 50, 50, fill='red', outline='red')

Opens a window with a red rectangle in the corner

Lecture 3.3 Interaction

Scale Widget
from Tkinter import *
master = Tk()
w = Scale(master, from_=0, to=100, orient=HORIZONTAL)
w.pack()
  • Draws a scale widget
  • Slider can be moved by the user
Interacting with the Widget
  • Want to do something when the user moves the slider
w = Scale(master, from_=0, to=100, orient=HORIZONTAL, command = update)

def update(duty):
    pwm.ChangeDutyCycle(float(duty))
  • Update function is called
  • Takes the slider value as an argument

你可能感兴趣的:([Mooc]IoT Course 4 The Raspberry Pi Platform and Python Programming for the Raspberry Pi)