[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 V2
  • 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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市骡湖,隨后出現(xiàn)的幾起案子峻厚,更是在濱河造成了極大的恐慌浦夷,老刑警劉巖劈狐,帶你破解...
    沈念sama閱讀 217,907評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件莲兢,死亡現(xiàn)場離奇詭異改艇,居然都是意外死亡谒兄,警方通過查閱死者的電腦和手機舵变,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評論 3 395
  • 文/潘曉璐 我一進店門赊豌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來熙兔,“玉大人艾恼,你說我怎么就攤上這事钠绍×” “怎么了蛾找?”我有些...
    開封第一講書人閱讀 164,298評論 0 354
  • 文/不壞的土叔 我叫張陵打毛,是天一觀的道長碰声。 經常有香客問我展辞,道長洽腺,這世上最難降的妖魔是什么蘸朋? 我笑而不...
    開封第一講書人閱讀 58,586評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮炼彪,結果婚禮上,老公的妹妹穿的比我還像新娘局义。我一直安慰自己檩帐,他們只是感情好湃密,可當我...
    茶點故事閱讀 67,633評論 6 392
  • 文/花漫 我一把揭開白布勾缭。 她就那樣靜靜地躺著,像睡著了一般目养。 火紅的嫁衣襯著肌膚如雪俩由。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,488評論 1 302
  • 那天癌蚁,我揣著相機與錄音幻梯,去河邊找鬼兜畸。 笑死,一個胖子當著我的面吹牛碘梢,可吹牛的內容都是我干的咬摇。 我是一名探鬼主播,決...
    沈念sama閱讀 40,275評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼在扰,長吁一口氣:“原來是場噩夢啊……” “哼皱卓!你這毒婦竟也來了存炮?” 一聲冷哼從身側響起融虽,我...
    開封第一講書人閱讀 39,176評論 0 276
  • 序言:老撾萬榮一對情侶失蹤寄悯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后怕膛,有當地人在樹林里發(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 45,619評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡个束,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,819評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片爱致。...
    茶點故事閱讀 39,932評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡纫普,死狀恐怖悦昵,靈堂內的尸體忽然破棺而出拦坠,到底是詐尸還是另有隱情晓铆,我是刑警寧澤链蕊,帶...
    沈念sama閱讀 35,655評論 5 346
  • 正文 年R本政府宣布忱嘹,位于F島的核電站分苇,受9級特大地震影響蘑斧,放射性物質發(fā)生泄漏。R本人自食惡果不足惜罐农,卻給世界環(huán)境...
    茶點故事閱讀 41,265評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧卦羡,春花似錦虏肾、人聲如沸吹埠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽墩弯。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背惭嚣。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留祷愉,地道東北人帆阳。 一個月前我還...
    沈念sama閱讀 48,095評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親山宾。 傳聞我的和親對象是個殘疾皇子至扰,可洞房花燭夜當晚...
    茶點故事閱讀 44,884評論 2 354

推薦閱讀更多精彩內容

  • 這本書看了兩遍,第一遍沒怎么看進去,只是機械地完成了閱讀,前后花了半年時間;第二遍花了半個月完成资锰,認識雖沒有很深刻...
    蝦米妖閱讀 849評論 0 2
  • 我在秋風中等待 等待一場秋雨的到來 她像個調皮的孩童 常光著身子在荷葉上跳蕩 喜歡在河面上畫圈 你看那門前的雨簾 ...
    不識字_6e51閱讀 237評論 0 0