[Mooc]IoT Course 2 The Arduino Platform and C Programming

Week 1 Arduino Environment

Lesson 1

Lecture 1.1 Arduino Platform

A development board
  • 8-bit microcontroller
  • programming hardware
  • USB programming interface
  • I/O pins
Arduino Environment
A software environment
  • cross-compiler
  • debugger
  • simulator
  • programmer
Special-purpose "Shields"
  • daughter boards
  • unique functionalities
  • easy to attach
  • good libraries provided
The Arduino Decelopment Board
  • Has a microcontroller and USB interface to a PC
  • Large open source community

Power/reset: Reset button; USB connector; Power connector

Lecture 1.2 Arduino Board

  1. Input/Output Pins: Digital I/O; Power/reset pins; Analog inputs
  2. Microcontrollers
    • ATmega328 is the processor programmed by the user
    • ATmega16U2 handles USB communication
  3. Two types of code executing on a simple mocrocontroller:
    • Application code
      • Executes the system's main functionality
      • We write this code
    • Firmware
      • Low-level code: supports the main function
      • USB interface, power modes, reset, etc.
    • The distinction is a matter of perspective
    • Arduino firmware is pre-programmed

Lecture 1.3 Direct Programming

Bootloader
  • Firmware on a microcontroller
  • Allows the Flash and EEPROM to be programmed
  • Manages USB communication, since application programming is via USB
In-Circuit Serial Programming (ICSP)
  • A special programming method to program the firmware
  • Needed because the bootloader can't reprogram itself

Lesson 2

Lecture 2.1 Arduino Schematics

Arduino UNO Schematic

  • Arduino designs are open source
  • Design is available
  • You can build your own

Lecture 2.2 Arduino IDE

IoTM2W1L2.2.png

Arduino Integrated Development Environment(IDE)

Lecture 2.3 Compiling Code

Compiling Code
  • Verify and Upload both compile
  • Message window will show either completion message or error messages
  • Error messages will show line numbers
Serial Monitor
  • Displays serial data sent from the Arduino
  • Allows serial data to be sent to the Arduino from the keyboard
  • Library functions in the serial library

Lesson 3

Lecture 3.1 Arduino Shields and Libraries

Arduino Shields
  • Add-on boards that interface with another device/IC
  • Can be stacked directly on top of the Arduino
  • Libraries exist to make interfacing simple
  • Open source hardware, but most can be purchased
  • Large variety of shields available
  • Big advantage of the Arduino platform
Some Arduino Shields

Ethernet Shield; Color LCD shield; Synhesizer Shield(generate music and connect to a speaker)

Ethernet Shield Library Example
  • Used by a client to establish a connection
  • Call the function, ignore the detail

Lecture 3.2 Arduino Basic Setup


Week 2 C Programming

C_Lesson1
C_Lesson2
C_Lesson3
C_Lesson4
C_Lesson5

Lesson 1

Lecture 1.1 Setting Up Your Environment

Getting Started
  • Prints "hello, world" to the screen
  • Type this in with a text editor and save it as hello.c
Running a Program
  • You will need a text editor and a compiler
    • Debugger will be needed later
  • I use GNU tools
    • emacs text editor
    • gcc C compiler
    • gdb C debugger
  • Can run on Windows but MacOS and Linux are easier
  • Eclipse Integrated Development Environment(IDE)(Windows)
    • Puts all tools together in a nice graphic user interface
    • Need Java Runtime Environment(JRE) to run it
    • Can also use Microsoft Visual Studio (not free)

Lecture 1.2 Hello World

Breaking Down Hello.c
    #include <stdio.h>
  • Tells the compiler to use the library functions described in stdio.h
  • printf (the print function) is inside stdio
  • Beginning of the main function
  • All code execution starts at main
    {}
  • Curly brackets group lines of code
  • All functions start and end with curly brackets
    printf(...);
  • Prints to the screen
  • The argument is in parenthesis
  • The argument is what is printed
  • Note the semicolon at the end
    main() {
        printf("hello, ");
        printf("world");
        printf("\n");
    }

"hello, world\n"

  • This is the argument to printf which appears on the screen
  • It's a string because it's in quotes("")
  • \n is a special character that indicates newline

Lecture 1.3 Variables

Variables
  • Names that represent values in the program
  • Similar to algebraic variables
  • All variables have a type which must be declared
    int x;
    float y;
  • Type determines how arithmetic is performed, how much memory space is required
Types and Type Qualifiers
  • Several built-in types,different sizes
Type Size Notes
char 1 byte Fixed size
int Typically word size 16 bit minimum
[float Floating point 64 bits, typical
double Double-precision 64, 128 typical
  • Type qualifiers exist: short, long
  • Char is 8 bits on all platforms
Variable Names
  • A sequence of visible characters
  • Must start with a non-numerical character
  • No C language keywords

Lesson 2

Lecture 2.1 Basic C Operators

Constants
  • Can use #define compiler directive
    #define ANSWER 42
  • Any instance of the string is substituted at compile time
  • Character constants
    • Written as a single character in single quotes
    • #define TERMINATOR 'x'
    • Integer equal to the ASCII value of the character
    • Some characters are not easy to represent(i.e. bell)
Arithmetic/Relational Operators
  • +,-,*,/
  • % is the modulo operator, division remainder
  • Ex. 9%2=1;9%3=0
  • ++(increment), --(decrement)
  • ==,<,>,<=,>=,!=
  • Ex. if(x<5)...
Logical Operators
  • && (AND),|| (or), ! (Not)
  • Treat argument as 1-bit binary values
    • 0 is FALSE, not-0 is TRUE
  • if((A==1)&&!B)

Lecture 2.2 Conditionals

Conditional Statements

if

if (expression)
    statement1
else
    statement2
if (expression)
    statement1
else if (expr2)
    statement2
else 
    stat3
  • else is optional
  • expression is evaluated
    • Executed statement1 if TRUE, statement2 if FALSE
  • expr2 evaluated if expr1 is FALSE

Switch

switch (expr) {
    case const_expr1: stat1
    case const_expr2: stat2
    default: stat3
}
  • expression is evaluated, compared to const_expr
  • Statements are executed corresponding to the first matching expression
  • default is optional
  • Without a break statement the case will not end

Lecture 2.3 Loops

While and For Loops
for (expr1; expr2; expr3)
    statement
expr1;
while(expr2) {
    statement
    expr3;
}
do {
    statement
    expr3;
} while (expr2);
  • Initialization and increment are built into the for loop
  • Condition checked at the top of a for/while loop
  • Condition checked at the bottom of a do-while loop
Break and Continue
  • Break jumps to the end of a for, while, do,case
  • Continue jumps to the next iteration of a loop

Lesson 3

Lecture 3.1 Functions

Functions
  • Functions can replace groups of instructions
  • Define a function; call a function
  • Naming is important
Function Arguments

Data can be passed to functions as arguments

Function Return Value
  • Functions can return a value to the caller
  • The type of the return value must be declared

Lecture 3.2 Global Variables

Global Variables
  • A variable is global if it's defined outside of any function
  • A global variable must be declared as an extern in any function using it
    • Extern not needed if global declaration is before the function
  • Variables can be global across files
Globals Are Dangerous
  • Global variables can propagate bugs
  • Bug in foo can cause bar to crash
  • Debugging can become harder
  • Reduce modularity of code

Week 3

BuildProcess
Setup
Loop
PinMode
DigitalWrite
DigitalRead
AnalogRead

Lesson 1 Arduino Programs

Lecture 1.1 Arduino Toolchain

Verify and Upload
IoTM2W3L1.1.png
Combine and Transform
  • All program files are combined into one
  • An #include is added to reference basic Arduino libraries
  • Function prototypes are added
  • A main() function is created

Lecture 1.2 Cross-Compilation

Compile and Link
  • avr-gcc is invoked to cross-compile the code
    • Resulting code executes on AVR, not Intel
  • Generates an object file(.o)
  • Object file is linked to Arduino library functions
Hex File Creation and Programming
  • avr-objcopy is invoked to change the format of the executable file
  • A .hex file is generated from the .elf file

Lecture 1.3 Arduino Sketches

Arduino Programs
  • A program is called a sketch
  • C++ program using Arduino library functions
  • C++ is a superset of C
    • All C programs are legal C++
  • C++ also includes classes
Object-Oriented Programming
  • Organize your code through encapsulation
  • Group together data and functions that are related
  • User-defined type is specific to an app
    • Ex. ints have data(the number) and functions (+,-,*)

Lesson 2

Lecture 2.1 Classes

Classes and Members
class X {
public:
    int m;
    int mf(int v) { int old = m; m=v ; return old; }
};

X var;
var.m = 7;
int é = var.mf(9);
  • Declaration of a variable creates an object
  • .Operator used to access members
    • Data and functions
  • Functions can be defined inside the class
Classes in Libraries
Ethernet.begin(mac);
Serial.begin(speed);
client.print("Hello");
Serial.print("Hello");
  • We don't need to know a lot about classes
  • We will not define classes
  • We will use classes defined in libraries

Lecture 2.2 Sketch Structure

Setup() Function
  • A sketch does not have a main() function
  • Every sketch has a setup() function
    • Executed once when Arduino is powered up
    • Used for initialization operations
    • Returns no value, takes no arguments
Loop() Function
  • Every sketch has a loop() function
    • Executed iteratively as long as the Arduino is powered up
    • loop() starts executing after setup() has finished
    • loop() is the main program control flow
    • Returns no value, takes no arguments

Lecture 2.3 Pins

Pins
  • Pins are wires connected to the microcontroller
  • Pins are the interface of the microcontroller
  • Pins voltages are controlled by a sketch
  • Pin voltages can be read by a sketch
Output Pins

Output pins are controlled by the Arduino

  • Voltage is determined by your sketch
  • Other components can be controlled through outputs
Input Pins
  • Input pins are controlled by other components
  • Arduino reads the voltage on the pins
  • Allows it to respond to events and data
Digital vs. Analog
  • Some pins are digital-only
    • Read digital input, write digital output
    • 0 volts or 5 volts
  • Some pins can be analog inputs
    • Can read analog voltages on the pin
    • Useful for analog sensors
  • Analog-only pins are clearly labeled
  • No pins can generate an analog output

Lesson 3

Lecture 3.1 Input and Output

Input/Output(I/O)
  • These functions allow access to the pins

    void pinMode(pin, mode)

  • Sets a pin to act as either an input or an output

  • pin is the number of the pin

    • 0-13 for the digital pins
    • A0-A5 for the analog pins
  • mode is the I/O mode the pin is set to

    • INPUT, OUTPUT, or INPUT_PULLUP
    • INPUT_PULLUP acts as input with reversed polarity
Digital Input
int digitalRead(pin)
  • Returns the state of an input pin
  • Returns either LOW(0 volts) or HIGH(5 volts)
Digital Output
void digitalWrite(pin, value)
  • Assigns the state of an output pin
  • Assigns either LOW(0 volts) or HIGH(5 volts)
Analog Input
int analogRead(pin)
  • Returns the state of an analog input pin
  • Returns an integer from 0 to 1023
  • 0 for 0 volts, 1023 for 5 volts

Lecture 3.2 Blink Examples

Delay
void delay(msec)
  • Pauses the program for msec milliseconds
  • Useful for human interaction
Blink Example
  • Blink is the generic simple example for embedded systems
    • Like "hello, world"

Week 4

Serial

Lesson 1

Lecture 1.1 Debugging

Debug and Trace

Controllability and observability are required

Controllability
  • Ability to control sources of data used by the system
  • Input pins. input interfaces(serial. ethernet, etc)
  • Registers and internal memory
Observability
  • Ability to observe intermediate and final results
  • Output pins output interfaces
  • Registers and internal memory
I/O Access Is Insufficient

Observation of I/O is not enough to debug

Properties of a Debugging Environment
  1. Run control of the target
    • Start and stop the program execution
    • Observe data at stop points
  2. Real-time monitoring of target execution
    • Non-intrusive in terms of performance
  3. Timing and functional accuracy
    • Debugged system should act like the real system

Lecture 1.2 Debug Environment

Remote Debugger
  • Fronted running on the host
  • Debug Monitor hidden on target
    • Typically triggered when debug events occur
    • Hitting a breakpoint, receiving request from host, etc.
  • Debug monitor maintains communication link
Remote Debug Tradeoffs

Advantages:

  1. Good run control using breakpoints to stop execution
  2. Debug monitor can alter memory and registers
  3. Perfect functional accuracy

Disadvantages:

  1. Debug interrupts alter timing so real-time monitoring is not possible
  2. Need a spare communication channel
  3. Need program in RAM(not flash) to add breakpoints
Embedded Debug Interfaces
  • Many modern processors include embedded debug logic
    • Typically an optional IP block
    • Embedded trace macrocell (ARM)
    • Background debug mode (Freescale)
  • Debug logic permanently built into the processor
  • A few dedicated debug pins are added
Debug and Trace Features
  • Breakpoints, stopping points in the code
  • Watchpoints, memory locations which trigger stop
  • On-the-fly memory access
  • Examine/change internal processor values
  • Single- step through the code
  • Export exceptions to the debugger(hit a watchpoint)
  • Export software-generated data(printf)
  • Timestamp information for each event
  • Instruction trace(special purpose HW needed)

Lecture 1.3 Debug via Serial

Serial Protocols
  • Data is transmitted serially
    • Only 1 bit needed (plus common ground)
  • Parallel data transmitted serially
  • Original bytes/words regrouped by the receiver
  • Many protocols are serial to reduce pin usage
    • Pins are precious
UART
  • Universal Asynchronous Receiver/Transmitter
  • Used for serial communication between devices
  • UART is asynchronous: no shared clock
  • Asynchronous allows longer distance communication
    • Clock skew is not a problem
UART
  • Used by modems to communicate with network
  • Computers used to have an RS232 port. standard
  • Not well used any more, outside of embedded systems
    • Replaced by USB, ethernet, I2C, SPI
  • Simple, low HW(Hardware) overhead
  • Built into most microcontrollers

Lesson 2

Lecture 2.1 UART Protocol

Simple UART Structure
IoTM2W4L2.1.png
  • Data is serialized by Tx, deserialized by Rx
  • Status indicates the state of the transmit/receive buffers
    • Used for flow control
UART Timing Diagram
IoTM2W4L2.1_2.png
  • First bit is the Start Bit: initiates the transfer
  • Next bits are the data
  • Last are the Stop Bits
Bit Duration
  • Each bit is transmitted for a fixed duration
  • The duration must be known to Tx and Rx
  • Baud rate(f) determines the duration(T)
  • Baud rate is the number of transitions per second
    • Typically measured in "bits per second(bps)"
  • T = 1/f
    • F = 9600 baud, T = ~104 microsec
  • Transmission rate is less than baud rate

Lecture 2.2 UART Synchronization

UART Synchronization
IoTM2W4L2.2.png
  • Receiver must know the exact start time
  • Imprecise start time corrupts data
Start Bit, Synchronization
IoTM2W4L2.2_2.png
  • Detection of the start bit is used to synchronize
    • Synchronization based on falling edge of start bit
  • Start bit is a falling edge
    • Following 0 must be long duration to screen out noise
  • Receiver samples faster than baud rate(16x typical)
  • Start bit indicated by a 0 of at least half period

Lecture 2.3 UART Parity and Stop

Parity Bit
  • Transmission medium is assumed to be error-prone
    • E-M radiation noise, synchronization accuracy
  • Parity bit may be transmitted to check for errors
    • Even Parity: Number of 1's is even
    • Odd Parity: Number of 1's is odd
  • Parity bit is added to ensure even/odd parity
    • After data, before stop bit(s)
  • Data = 011011010
    • Parity bit = 1, total parity is odd
Stop bit
  • Receiver expects a 1 after all data bits and parity bits
  • If 1 is not received, an error has occurred
Data throughput vs. Baud
  • Every transmission involves sending signaling bits
    • Stop, start, parity
  • Data throughput rate is lower than baud rate
    • Signaling bits must be sent
  • 8 data bits, 1 parity bit, baud rate = 9600
    • Send 1& bits to send 9 data bits
    • Transmission efficiency = 8/11 = 73%
    • Data throughput rate = 9600*0.73 = 6981.8 bps

Lesson 3

Lecture 3.1 Serial on Arduino

Arduino Serial Communication
  • UART protocol used over the USB cable
  • Initialize by using Serial.begin()
  • Serail.begin(speed) or Serial.begin(speed, config)
  • speed is the baud rate
  • config sets the data bits, parity, and stop bits
  • Serial.begein(9600)
  • Serial.begein(9600, SERIAL_8N1)
    • 8 data, no parity, 1 stop
  • Usually call Serial.begin() in the setup function
Sending Text Over Serial
  • Use Serial.print() or Serial.println() to print text in the monitor
  • Strings are converted to ASCII and sent using UART
  • Use Serial.write()
  • Serial monitor still interprets data as ASCII
  • 42 is the ASCII value for '*'

Lecture 3.2 Reading from Serial

Reading Data Over Serial
  • Data can be sent to the Arduino via the serial monitor
  • When data is sent it goes into a buffer in the Arduino until it is read
  • Serial.available() is used to see how many bytes are waiting in the buffer
Serial.read()
  • Returns 1 byte from the serial buffer

      int bval = Serial.read();
    
  • Returns -1 if no data is available

  • Serial.readBytes() writes several bytes into a buffer

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

推荐阅读更多精彩内容

  • Week 1 Reading Material Lesson 1 Lecture 1.1 Raspberry Pi...
    Vinchent阅读 500评论 0 1
  • Week 1 Reading a schematic Using a breadboard Resistors...
    Vinchent阅读 425评论 0 1
  • 文 | 王大可 我走出校园后的第一个工作地点,在公司承包了生产经营的一家酒厂。我和其他几位同事组成的“外派机构”进...
    王大可的观阅读 176评论 0 1
  • (一) 她是我的母亲。 她在户口簿上的名字是“乐冬女”,是因为生在阴历十二月的缘故吧。这个名字应了出生月份,大俗中...
    晨风微凉阅读 545评论 15 12
  • 天色阴沉 沙哑的风 灌满空旷的路口 沉闷的汽笛声 托慢了北飞的归鸟 海上的孤岛 沉没所有的地图 自己定位月的距离 ...
    带路阅读 160评论 2 1