[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
[Mooc]IoT Course 3 Interfacing with the Arduino_第1张图片
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第2张图片
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第3张图片
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第4张图片
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 
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第5张图片
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第6张图片
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第7张图片
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第8张图片
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第9张图片
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
[Mooc]IoT Course 3 Interfacing with the Arduino_第10张图片
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 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

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

你可能感兴趣的:([Mooc]IoT Course 3 Interfacing with the Arduino)