[Mooc]IoT Course 3 Interfacing with the Arduino

Week 1

Reading a schematic
Using a breadboard
Resistors
Diodes
LEDs

Lesson 1

Lecture 1.1 Electrical Circuits

Hardware and Software
  • IoT devices combine hardware and software
  • Hardware interacts with the world
  • Software is the "intelligence"
Electrical Circuits
  • Electrical current flowing though wires
  • Battery/power supply moves current

Lecture 1.2 Electrical Properties

Voltage
  • Voltage(V) : Potential difference between two points in the circuit
  • Like pressure in a water system
  • Pressure difference is what counts
  • Measured in volts
Current
  • Current(I) : Rate of carrier flow
  • Flows from positive to negative
  • Electrons flow from negative to positive
  • Measured in amperes
Resistance
  • Resistance(R) : Any obstacle to current flow
  • For water, might be a rock or narrow pipe
  • For circuits, might be a bad conductor or narrow conductor

Lecture 1.3 Ohm's Law

Ohm's Law

V=I*R

  • Expresses the relationship between V,I and R
  • Used to compute one value given the other 2
  • Some common uses:
    • What resistor do I need to limit current flow
    • What voltage can I expect for a given resistance

Lesson 2

Lecture 2.1 Electrical Components

Resistors
  • Provides resistance to current flow
  • Two terminals; no difference between them
  • Band colors indecate resistor size
    • Each color is a digit; scientific notation is used
Battery/DC Power
  • Provides voltage via power and ground
  • Do not Create a short circuit

Lecture 2.2 Diodes

Diodes and LEDs
  • Two terminals: Anode > Cathode
  • Current only flows in one direction, anode to Cathode
    • One-way valve
  • LEDs light when current flows
Diode Threshold Voltage
  • Anode-Cathode voltage must be above threshold
    • Threshold depends on diode
  • Reverse-biased: when anode is negative wrt cathode
Diode Current Limit
  • Diodes have a maximum current limit
  • Maybe 20 mA
  • Do not connect an LED directly across a 5V supply
    • Too much current without a resistor

Lecture 2.3 Switches, Potentiometers

Switch/Pushbuttons
  • Closing the switch completes the circuit
  • Voltage on both terminals is identical when switch is closed
Potentiometer
  • Three terminals: top, bottom, middle
  • Resistance between top and bottom terminals is constant
  • Ratio of resistances changes

Lesson 3

Lecture 3.1 Wiring

Interpreting a Schematic
  • Shows how components are connected in real circuit
  • You need to be able to build a real circuit from a schematic
  • You need to be able to draw a schematic to represent your design
Solderless Breadboard
  • Allows components to be easily connected in a non-permanent way
  • Great for prototyping
  • Holes fit 24 AWG solid wire
  • Connected in rows of 5 holes and columns along the slides
Wiring Process
  1. Select a hardware component
  • Select one terminal on the hardware component
  • Connect the terminal to a row of the breadboard
    • if the terminal needs to be connected to another terminal already in the breadboard, share the row
    • Otherwise, use a free row
  • Go back to step 2 until all terminals are done
  • Go back to step 1 until all components are done

Lecture 3.2 Wiring Demo, Pushbutton

Lecture 3.3 Wiring Demp, Potentiometer


Week 2

Sensor Types
Pulse Width Modulation
analogWrite

Lesson 1

Lecture 1.1 Sensors

Sensors
  • Allow the microcontroller to receive information about the environment
    • How bright is it?
    • How loud is it?
    • How humid is it?
    • Is the button being pressed
  • Perform operations based on the state of the environment
  • Turn on a light if it's dark out
    • Voice-controlled operation
Sensing the Environment
  • Microcontrollers sense voltage
    • digitalRead(pin) returns state of a digital pin
    • analogRead(pin) returns the analog voltage on a pin
  • Sensor logic must convert an environmental effect into voltage
Reading a Pushbutton
IoTM3W2L1.1.png
  • Make a pin high when the button is pressed and low when it is not pressed
  • Wrong circuit leaves pin open when not pressed

Lecture 1.2 Resistive Sensor

Resistive Sensors
IoTM3W2L1.2.png
  • Many sensors change resistance
    • Photoresistor, thermistor, flex resistor,etc.
  • Connect sensor in a voltage divider
  • As resistance changes, voltage changes
Photoresistor
  • As brightness increases, resistance decreases
  • Resistance = 10K Ohms, voltage = 2.5 Volts
  • Resistance = 5K Ohms, voltage = 3.33 Volts
Voltage-Controlling Sensors
IoTM3W2L1.2_2.png
  • Some sensors control voltage directly
  • Signal is pulled low when motion is detected
  • Open-collector - signal floats without motion
Other Voltage Controlling Sensors
  • Accelerometer reports acceleration in 3 dimensions
  • Gyroscope reports angular velocity in 2 dimensions

Lecture 1.3 Resistive Sensor Demo

Lesson 2

Lecture 2.1 Actuators

Actuators
  • Devices that cause something to happen in the physical world
  • Outputs of the IoT device
    • Visual: LED,LCD, monitor
    • Audio: buzzer,speaker
    • Motion: motors, valve, pump
    • Tactile: heating, cooling
On-Off Actuation
  • The only control is power
  • Even complicated actuators can be controlled via power
    • LED, buzzer, monitor,etc.
  • Does not use the full potential of the actuator
  • On-Off control may be all that is necessary
    • Lights in a class room, air conditioning
Current Limits
  • Watch out for current limits
  • LED can only handle 20mA
    • Be sure to use an appropriate resistor
  • Arduino can only supply 40 mA
    • Cannot drive a motor that requires 15 Amperes!
    • May need to use alternate power supply
    • Arduino can control access to power without providing power directly

Lecture 2.2 Analog Actuators

Analog Voltage Control
  • Many actuators need an analog voltage for complete control
    • DC motor speed controlled by voltage
    • LED brightness controlled by voltage
    • Heating element temperature controlled by voltage
  • Arduino cannot generate analog outputs
Digital to Analog Converter(DAC)
  • DAC will convert digital number to an analog voltage
  • Most microprocessors do not have a DAC
  • Can buy one and attach it
  • May be costly

Lecture 2.3 Pulse Width Modulation

Pulse Width Modulation
IoTM3W2L2.3.png
  • Duty Cycle is the percent of time the pulse is high
  • Increasing duty cycle increases perceived voltage
analogWrite()
  • Generates a square wave on a pin, 490 Hz
  • First argument is the pin number
  • Second argument is the pulse width
    • 0 is 0% duty cycle
    • 255 is 100% duty cycle
  • Pin number must be a PWM pin
    • Marked on the Arduino with the ~ symbol
  • Ex. analogWrite(3,128);
Fade Example
int brightness = 0;
int fadeAmount = 10;
void setup() {
    pinMode(led, OUTPUT);
}
void loop() {
    analogWrite(led, brightness);
    brightness = brightness + fadeAmount;
    if (brightness == 0 || brightness == 255)
        fadeAmount = - fadeAmount ;
    delay(30);
    }        

Lesson 3

Lecture 3.1 Demo Fade Example

Lecture 3.2 Making Sounds

tone()
  • tone() can generate a square wave with an arbitrary frequency
    • analogWrite() has fixed frequency
  • Duty cycle is fixed at 50%
  • Can be used to drive a speaker or buzzer
  • Two or three arguments
    • Pin number
    • Frequency, in Hz
    • Duration in ms (optional)
Square Waves vs. Sine Wave
  • Square waves sound bad
    • Many high-frequency components
  • Square wave is the best we can do with digital outputs
Piezo Element, Buzzer
  • Two inputs: signal and ground
  • Produces a click when a rising edge is applied
  • Driving with a square wave produces a pitch
Music System
void setup() {
}
void loop() {
    tone(8, 988, 1000);
    delay(1000);
    tone(8, 1047, 1000);
    delay(1000);
}
  • Plays two tones, 1 sec each
  • Delay is needed; only one tone at a time

Lecture 3.3 Demo Music System


Week 3

EEPROM Library
Wire Library
SPI Library
Servo Library

Lesson 1

Lecture 1.1 Arduino Libraries

Arduino Libraries
  • Many devices are more complicated then simple sensors/ actuators
  • Microcontroller (ATMega328) has components which are hard to use
    • Memories, communication interfaces, PWM logic, etc.
  • Arduino provides libraries to facilitate their use
  • Libraries are also available for external hardware
    • Wifi controller, LCD, GSM controller
EEPROM
  • Electronically Erasable Programmable Read-Only Memory(EEPROM)
  • Non-volatile memory; holds data without power
  • Similar to Flash but more flexible
    • Write a single byte at a time
    • Supports many more write cycles
  • Only 1024 bytes available on ATMega328
Reading and Writing
  • Access one address at a time
  • Each address contains one byte
  • EEPROM.read(address) : returns the contents of an address
  • EEPROM.write(address, data) : write a single byte of data into the address
  • Address must be between 0 and 1023

Lecture 1.2 EEPROM

Reading and Writing
#include <eeprom.h>
Void setup() {
    int addr;
    Serial.begin(9600);
    for (addr=0; addr<1024; addr++) {
        EEPROM.write(addr, addr);
    }
    for (addr=0; addr<1024; addr++) {
        Serial.print(EEPROM.read(addr), DEC)
    }
}
Multiple Bytes
  • Can only read/write one byte at a time
  • How do you deal with larger numbers?
    • Int is 2 bytes long
  • Use masking to access a single byte at a time
  • Mask is a series of bits that highlights the bits in the number that you are interested in
  • Performing a bitwise and operation with the mask zeroes out run-interesting bits

Lecture 1.3 Masking

Masking
IoTM3W3L1.3.png
Masking High Bits

259>>8
(259>>8)&255

Writing an int to EEPROM
int bigData;
byte littleData;
void setup() {
    littleData = bigData & 0xFF;
    EEPROM.write(0, littleData);
    littleData(1, littleData);
}

Little Endian ordering

Lesson 2

Lecture 2.1 I2C Communication

I2C Communication Protocol
  • Synchronous, serial protocol
  • Multiple masters, multiple slaves
  • Bitwidth is fixed, independent of number of slaves
  • Two wires: SDA (serial data) and SCL (serial clock)
  • Both lines are open-drain
    • Pulled up to high by default
    • State of bus is always known
I2C Terminology
  • Master - Initiates and terminates transmission; generates Scl
  • Slave - Addressed by the Master
  • Transmitter - Placing data on the bus
  • Receiver - Reading data from the bus
I2C Network
IoTM3W3L2.1.png

SDA and SCL are bidirectional

Lecture 2.2 I2C Transactions

I2C Transaction Structure
  • Start Condition
    • Indicates the beginning of a transaction
  • Address/Direction Byte
    • Specifies slave for communication
    • Specifies read vs. write transaction
  • Data Byte(s)
    • Transmitted by either master or slave
  • Stop Condition
    • Indicates the end of a transaction
Start and Stop Conditions
IoTM3W3L2.2.png
  • Start Condition
    • Falling transition on SDA while SCL=1
  • Stop Condition
    • Rising trasition on SDA while SCL=1

Lecture 2.3 Sending Bits

Sending a bit
IoTM3W3L2.3.png
  • SDA is sampled by receiver on the rising edge of SCL
  • SDA must be constant where SCL is high
    • Exception is Start/Stop Condition
Acknowledge Bit
IoTM3W3L2.3_2.png
  • After each byte is sent, the receiver must acknowledge
  • Transmitter releases SDA, receiver must pull SDA low
    • Must be low for one pulse of SCL
  • If SDA is not pulled low, transmission is aborted
Typical I2C Transaction
IoTM3W3L2.3_3.png
  • Each slave has a unique 7-bit address
  • Direction bit: 0 indicates write, 1 indicates read

Lesson 3

Lecture 3.1 Wire Library

Wire Library
  • The wire library is used to access I2C
  • #include <Wire.h> needed at the top
  • Wire.begin()function initializes I2C hardware
  • Calling Wire.begin() with no arguments makes the Arduino a Master
  • Calling Wire.begin(addr) with an address makes the Arduino Slave
Master Communication
  1. Start the transmission
  • Send data

  • End the transmission

    • Data is put into a buffer before sending
    • Wire.beginTransmission(address) : Start condition and address are initialized
    • Wire.write(data) : Buffers data for sending
    • Wire.endTransmission() :
      • Transmits data in buffer
      • Returns a status byte, 0 for success
Master Transmission Example
#define ADDR 1;
void setup() {
    Wire.begin();
    Wire.beginTransmission(ADDR);
    Wire.write(2);
    Wire.write(3);
    Wire.endTransmission(stop);
}
  • Send two bytes
  • Stop condition sent at the end

Lecture 3.2 Master Communication

Master Read
  • Wire.requestFrom() : used to specify a read transaction
  • Three arguments
    1. Address of the slave
    2. Number of bytes to read
    3. Optional stop argument to release the bus after
  • Wire.read() : returns a single byte from the receive buffer
  • Wire.available() : returns number of bytes waiting
Master Receiver Example
int sum = 0;
Wire.requestFrom(AddR, 2);
while (Wire.available())
    sum += (int) Wire.read();
  • Receive two bytes from the slave, compute sum
  • Wire.available() is used to check how much data is received

Lecture 3.3 Slave Operation

Slave Operation
  • Slave must wait for a transmission, cannot initiate
  • Busy wait loops are wasteful
  • Callback functions: functions called when an event occurs
  • Wire.onReceive() : identifies the function called when the slave receives data from a master (write transaction)
  • Wire.onRequest() : identifies the function called when data is requested from the slave (read transaction)
typical Slave Receive Code
void receiveFunct(int byteMum) {
    int i, sum = 0;
    for (i=0; i<byteNum; i++)
        sum += WIre.read();
    Serial.print(sum);        
}
Wire.onReceive(receiveFunct);

Callback must take one argument, number of bytes received

Typical Slave Transmit Code
void transmitiFunct(void) {
    Wire.write(SOME_DATA_BYTE);
}

Wire.onRequest(transmitFunct);

Callback must take no arguments, return nothing


Week 4

About Arduino Shields
Arduino Shield List (Don't memorize, just reference)
Ethernet Shield
WiFi Shield

Lesson 1

Lecture 1.1 Arduino Shields

A Arduino shields

  • shield : a printed circuit board (PCB) that adds functionality to your Arduino
  • Hardware : A circuit is pre-wired and sold on a printed circuit board
  • Software : A software library is provided to interact with the hardware
Benefits of Shields
  • No wiring needed
    • Circuit is pre-wired
    • Connections to Arduino are fixed by stacking
  • Simple to use
    • Library takes care of complicated details
Connected Pins
  • Pins on the bottom of the shield connect to pins of the Arduino
  • Most shields only use a small subset of the pins
  • Need to know which pins are used when using multiple shields
  • Shield headers may need to be soldered

Lecture 1.2 Ethernet Shield

Ethernet Shields
  • Allow internet connections through a wired interface
  • Shield includes an Ethernet jack (RJ45) for a network cable
  • Several shields are available
  • Common library is used
Internet Addresses
  • Mac address : unique address "hardwired" into each network adapter. 6 bytes long
  • IP address : address used for addressing by internet protocols. 4 bytes long
  • Port : number identifying the application protocol being used. 2 bytes long
Domain Name Service
  • Service that maps domain names to IP addresses
  • Names are much easier to memorize than IP addresses
  • DNS servers store the mapping
  • Internet servers/clients may need to be configured with a DNS server

Lecture 1.3 Ethernet Library

Ethernet #include
  • There are many .h files to include
    • Ethernet.h
    • EthernetClient.h
    • EthernetServer.h
  • sketch-->Import; Library-->Ethernet
Initializing the Ethernet
  • Invoke the Ethernet.begin() function
  • 5 possible arguments, only the first is required
  • MAC Address(required)
  • IP Address
  • DNS : Address of the domain name server
  • Gateway : Address of a router which knows how to forward packets to other networks
  • Subnet mask : Mask which specifies the local network(i.e. 2555.2555.255.0)
Dynamic Host Connection Protocol
  • Every node on the internet needs an IP address
  • DHCP allows the IP address to be assigned dynamically
  • DHCP is invoked if Ethernet.begin() has no IP address argument
  • Most routers are configured for DHCP
  • static IP addresses are typical for servers

Lesson 2

Lecture 2.1 Ethernet Client

Ethernet Client
  • Arduino can act as a client, create a client object
    • EthernetClient client;
  • Needs to connect to a server
    • result = client.connect;
    • result = client.connect(domain, port);
    • Returns 1 if connection is made, 0 if it is not
Sending and Receiving Data
  • client.print(data); and client.println(data); send data
  • println() adds a carriage return data is a string or an array of bytes
  • client.write(value); sends a raw byte
  • data = client.read(); reads the next byte
  • result = client.available(); returns 1 if data is waiting

Lecture 2.2 Client Examples

Client Sends Data
byte mac[]={0xDE, 0xAD, 0xBE, 0xEF, 0x12, 0x34};
char server[]= "testdomain.edu";
EthernetClient client;
void setup() {
    Ethernet.begin(mac);
    if (client.connect(server, 80)) {
        client.println("GET index.html HTTP/1.1");
        client.stop();
    }
}
  • Sends a GET request to a web server
  • Port 80 used for the web
CLient Receives Data
void loop() {
    if (client.available())
        Serial.print (client.read());
}
  • Receives the response from the web server
  • Sends data to serial monitor

Lecture 2.3 Ethernet Server

Ethernet Server
  • Arduino can act as a server, create a server object
  • EthernetServer server = EthernetServer(port);
    • Port argument is the port that the server listens to
  • To start listening, server must create a client object EthernetClient client = server.available();
  • client object will be false(0) if client is not available
  • client.stop(); will close connection with client
  • Use client.print() and client.write() to send data
  • Use client.read() to read data
Server Receives Data
EthernetServer server = EthernetServer(80);
void setup() {
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();
}

void loop(){
    EthernetClient client = server.available();
    if (Client) {
        Serial.print(client.read());
    }
}

Lecture 2.4 Ethernet Shield Demo

Lesson 3

Lecture 3.1 WiFi Shield

WiFi Shield
  • Allows internet connections through a wireless interface
  • IEEE 802.11 (WiFi) standard is used
  • Library is similar to the Ethernet library
WiFi Initialization
  • Wifi.begin(); -no arguments; just initializes the shield
  • Wifi.begin(ssid); -connects to the network ssid
  • Wifi.begin(ssid, keyindex, key); -connects to ssid with key as WEP password
    • WEP can have up to 4 keys
    • keyindex indicates which key to use
WiFi Client and Server
  • Same as Ethernet client and server process
  • WiFiClient:
    • WiFiClient client;
    • result = client.connect (ip, port);
    • client.stop();
  • WiFiServer: slightly different
    • WiFiServer server(port);
    • Server.begin(); -starts server listening on port
Scanning WiFi Networks
  • Which network(SSID) should you connect to?
  • netnum = WiFi.scanNetworks(); -Returns the number of networks available
  • ssid = WiFi.SSID(i); -Returns the SSID of the N°i network(-90 to 0)
  • enc = WiFi.encryptionType(i); -Returns the encryption type used in the N°i network

Lecture 3.2 WiFi Shield Demo

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

推荐阅读更多精彩内容

  • Week 1 Arduino Environment Lesson 1 Lecture 1.1 Arduino P...
    Vinchent阅读 2,217评论 0 1
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,805评论 0 0
  • 柔美的月光撒满寂静的街道 陌色流年轻舒漫卷 品尝世事百味 曾经的焰火惊艳了岁月 那些从荒芜到繁华 镌刻着深深浅浅的...
    陶韵阅读 157评论 0 2
  • 好紧张,明天就要考试了,刚才做模拟题,心里好没底。但是我知道我从来都是那个幸运儿,我肯定会过的。你也会保佑我的,加...
    我和我的小太阳阅读 96评论 0 0
  • 现实,想逃逃不掉;折磨,想忘忘不了。这就是生活,仿佛一锅水,而我却是锅里的鱼,时间把水慢慢的烧开,我在里面经历煎熬...
    婕婕闪白白阅读 352评论 0 2