[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+
IoTM4W1L1.1.png
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
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
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
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]
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 <condition>:
    <indented code block>
<non-indented statement>

Example:

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

Template:

if <condition>:
    <indented code 1>
else:
    <indented code 2>
<non-indented statement>

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+
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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,588评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,456评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,146评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,387评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,481评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,510评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,522评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,296评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,745评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,039评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,202评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,901评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,538评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,165评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,415评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,081评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,085评论 2 352

推荐阅读更多精彩内容

  • 这本书看了两遍,第一遍没怎么看进去,只是机械地完成了阅读,前后花了半年时间;第二遍花了半个月完成,认识虽没有很深刻...
    虾米妖阅读 842评论 0 2
  • 我在秋风中等待 等待一场秋雨的到来 她像个调皮的孩童 常光着身子在荷叶上跳荡 喜欢在河面上画圈 你看那门前的雨帘 ...
    不识字_6e51阅读 236评论 0 0