arduino basics

Post on 14-Jan-2017

398 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

LTKA Labs

Arduino BasicsEueung Mulyana

http://eueung.github.io/ET3010/arduinoET-3010 | Attribution-ShareAlike CC BY-SA

1 / 44

Outline

Short Intro

Quick Start

Networking

MQTT

2 / 44

Short Intro

3 / 44

ArduinoAn open-source hardware and software platform for building

electronics projects.

Arduino is an open-source electronics platform based oneasy-to-use hardware and software. It's intended foranyone making interactive projects.

Arduino senses the environment by receiving inputs frommany sensors, and affects its surroundings by controllinglights, motors, and other actuators.

You can tell your Arduino what to do by writing code inthe Arduino programming language and using theArduino development environment.

Several Arduino-Board variants exist e.g.: UNO, NANO,MEGA, DUE, YUN, etc.

4 / 44

 

5 / 44

 

6 / 44

7 / 44

Quick Start

8 / 44

9 / 44

This ChecklistPlease:

UNO BoardCompatible +Acessories

Components +Wires

ARDUINO IDE

10 / 44

 

11 / 44

 

Tools - Config12 / 44

 

Sketch Upload13 / 44

14 / 44

15 / 44

Project #1 

13 12 11 10

9 8 7 6 5 4 3 2

L

5V A0

ANALOG IN

AREF

1

GND

TXRX

RESET

3V3

A1

A2

A3

A4

A5

VIN

GND

GND

DIGITAL (PWM= )

Arduino TM

IOREF

ICSP

ICSP2

ON

POWER

01TX

0

RX0RESET

11

55

1010

1515

2020

2525

3030

A A

B B

C C

D D

E E

F F

G G

H H

I I

J J

Fritzing Breadboard

16 / 44

Project #1 

D0/RX

D1/TXD

2

D3 PW

MD4

D5 PW

M

D6 PW

MD7

D8

D9 PW

M

D10 PW

M/SS

D11 PW

M/M

OSI

D12/M

ISO

D13/SCK

RESET

RESET2

AREF

ioref

A0

A1

A2

A3

A4/SD

A

A5/SCL

N/C

GND

3V3

5V

VIN

ArduinoUno

(Rev3)

21

211

2

12

13

2

Part1

LED1

Red (633nm)

R1100Ω

R210kΩ

S1R310kΩ

Fritzing Schematic

17 / 44

Project #1 Sketchint inPin = 2; int outPin = 3; int potPin = A0;

int state = LOW; int reading; int previous = LOW;

long time = 0; long debounce = 1000;

int potVal = 0; int prevPotVal = 0;

void setup() { Serial.begin(9600); delay(500);

pinMode(inPin, INPUT); pinMode(outPin, OUTPUT); Serial.println("Program started ...");}

void loop() { reading = digitalRead(inPin);

if (reading && (millis() - time > debounce)) { if (previous == LOW) { Serial.println("[PHYSICAL] LED turned on"); state = HIGH; } else { Serial.println("[PHYSICAL] LED turned off"); state = LOW; }

time = millis(); digitalWrite(outPin, state); previous = state; prevPotVal = potVal - 10; } potVal = analogRead(potPin); if((state == HIGH) && (abs(potVal-prevPotVal)>4)){ analogWrite(outPin, potVal/4); Serial.print("[PHYSICAL] LED intensity "); Serial.println(potVal/4); prevPotVal = potVal; }}

18 / 44

19 / 44

 

Serial Monitor20 / 44

Networking

21 / 44

UNO + Ethernet Shield 

13 12 11 10

9 8 7 6 5 4 3 2

L

5V A0

ANALOG IN

ARE

F

1

GND

TXRX

RESET

3V3

A1

A2

A3

A4

A5

VIN

GND

GND

DIGITAL (PWM= )

Arduino TM

IOREF

ICSP

ICSP2

ON

POWER

01TX

0

RX0RESET

13 12 11 ETH 9 8 7 6 5

SDCS

3 2 01TX RXARE

F

GND

5V A0

ANALOG IN

TX

RX

RESET

3V3

A1

A2

A3

A4

A5

VIN

GND

GND

DIGITAL (PWM SPI )

SCL SDA

<

IOREF

ICSP

CS

< <

22 / 44

23 / 44

Example #1 Web Server#include <SPI.h>#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};IPAddress ip(192, 168, 0, 177);

EthernetServer server(80);

void setup() { Serial.begin(9600); while (!Serial) {}

Ethernet.begin(mac, ip); server.begin(); Serial.print("Server is at "); Serial.println(Ethernet.localIP());}

void loop() { // ...}

EthernetClient client = server.available(); if (client) { Serial.println("new client"); boolean currentLineIsBlank = true;

while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); if (c == '\n' && currentLineIsBlank) { client.println("HTTP/1.1 200 OK"); client.println( client.println("Refresh: 5"); client.println();

client.println("<!DOCTYPE HTML>"); client.println( for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); client.print("analog input "); client.print(analogChannel); client.print( client.println("<br />"); } client.println("</html>"); break; } if (c == '\n') { currentLineIsBlank = true; } else if (c != '\r') { currentLineIsBlank = false; } } } // while

delay(1); client.stop(); Serial.println("client disconnected"); }

24 / 44

25 / 44

Test$> ping 192.168.0.177

Pinging 192.168.0.177 with 32 bytes of data:Reply from 192.168.0.177: bytes=32 time=2ms TTL=128Reply from 192.168.0.177: bytes=32 time=3ms TTL=128Reply from 192.168.0.177: bytes=32 time=2ms TTL=128Reply from 192.168.0.177: bytes=32 time=2ms TTL=128

Ping statistics for 192.168.0.177: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),Approximate round trip times in milli-seconds: Minimum = 2ms, Maximum = 3ms, Average = 2ms

Server is at 192.168.0.177new clientGET / HTTP/1.1Host: 192.168.0.177Connection: keep-aliveCache-Control: max-age=0Accept: text/html,application/xhtml+xml,application/xml;q=0.9Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/Referer: http://192.168.0.177/Accept-Encoding: gzip, deflate, sdchAccept-Language: en-US,en;q=0.8

client disconnectednew clientGET /favicon.ico HTTP/1.1Host: 192.168.0.177Connection: keep-aliveUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/Accept: */*Referer: http://192.168.0.177/Accept-Encoding: gzip, deflate, sdchAccept-Language: en-US,en;q=0.8

client disconnected

26 / 44

 

Browser

27 / 44

 

Serial Monitor28 / 44

Example #2 Web ClientSingle Request

#include <SPI.h>#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};IPAddress ip(192, 168, 0, 177);char server[] = "www.google.com";

EthernetClient client;

void loop() { if (client.available()) { char c = client.read(); Serial.print(c); }

if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop();

while (true); }}

void setup() { Serial.begin(9600); while (!Serial) { }

if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP" Ethernet.begin(mac, ip); } delay(1000); Serial.println("connecting...");

if (client.connect(server, 80)) { Serial.println("connected");

client.println("GET /search?q=arduino HTTP/1.1"); client.println("Host: www.google.com"); client.println("Connection: close"); client.println(); } else { Serial.println("connection failed"); }}

29 / 44

Example #3 Web ClientRepeated Requests

#include <SPI.h>#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};IPAddress ip(192, 168, 0, 177);char server[] = "www.arduino.cc";

EthernetClient client;

unsigned long lastConnectionTime = 0; const unsigned long postingInterval = 10L * 1000L;

void setup() { Serial.begin(9600); while (!Serial) {}

delay(1000); Ethernet.begin(mac, ip);

Serial.print("My IP address: "); Serial.println(Ethernet.localIP());}

void loop() { if (client.available()) { char c = client.read(); Serial.write(c); }

if (millis() - lastConnectionTime > postingInterval) { httpRequest(); }}

void httpRequest() { client.stop();

if (client.connect(server, 80)) { Serial.println("connecting...");

client.println("GET /latest.txt HTTP/1.1"); client.println("Host: www.arduino.cc"); client.println("User-Agent: arduino-ethernet"); client.println("Connection: close"); client.println();

lastConnectionTime = millis(); } else { Serial.println("connection failed"); }}

30 / 44

MQTT

31 / 44

IoT ProtocolsThe IoT needs standard protocols. Two of the most promisingfor small devices are MQTT and CoAP.

MQTT gives flexibility in communication patterns and acts purelyas a pipe for binary data.

CoAP is designed for interoperability with the web.

Both MQTT & CoAP:

Are open standardsAre better suited to constrained environments than HTTPProvide mechanisms for asynchronous communicationRun on IPHave a range of implementations

See: MQTT and CoAP, IoT Protocols

32 / 44

ArchitectureCoAP packets are much smaller than HTTP TCP flows. Bitfieldsand mappings from strings to integers are used extensively tosave space. Packets are simple to generate and can be parsed inplace without consuming extra RAM in constrained devices.

CoAP runs over UDP, not TCP. Clients and servers communicatethrough connectionless datagrams. Retries and reordering areimplemented in the application stack. Removing the need forTCP may allow full IP networking in small microcontrollers. CoAPallows UDP broadcast and multicast to be used for addressing.

CoAP follows a client/server model. Clients make requests toservers, servers send back responses. Clients may GET, PUT,POST and DELETE resources.

CoAP is designed to interoperate with HTTP and the RESTful webat large through simple proxies.

Because CoAP is datagram based, it may be used on top of SMSand other packet based communications protocols.

CoAPCoAP is the Constrained Application Protocol from the CoRE(Constrained Resource Environments) IETF group.

ArchitectureLike HTTP, CoAP is a document transfer protocol. Unlike HTTP,CoAP is designed for the needs of constrained devices.

33 / 44

MQTTMQTT is a publish/subscribe messaging protocol designed forlightweight M2M communications. It was originally developedby IBM and is now an open standard. It was designed in 1999for use on satellites and as such is very light-weight with lowbandwidth requirements making it ideal for M2M or IoTapplications.

ArchitectureMQTT has a client/server model, where every sensor is a clientand connects to a server, known as a broker, over TCP.

MQTT is message oriented. Every message is a discrete chunk ofdata, opaque to the broker.

Every message is published to an address, known as a topic.Clients may subscribe to multiple topics. Every client subscribedto a topic receives every message published to the topic.

34 / 44

MQTTFor example, imagine a simplenetwork with three clients and acentral broker.

All three clients open TCPconnections with the broker. ClientsB and C subscribe to the topictemperature .

At a later time, Client A publishes avalue of 22.5 for topic temperature .The broker forwards the message toall subscribed clients.

The publisher subscriber modelallows MQTT clients tocommunicate one-to-one, one-to-many and many-to-one.

35 / 44

MQTT - Publish / Subscribe

The publish / subscribe (often called pub-sub) pattern lies at the heart of MQTT. It's basedaround a message broker, with other nodes arranged around the broker in a star topology.This is a very different model to the standard client/server approach, and at first it mightseem a little strange, but the decoupling it provides is a huge advantage in many situations.

Clients can publish or subscribe toparticular topics which aresomewhat like message subjects.They are used by the broker todecide who will receive a message.

Topics in MQTT have a particularsyntax. They are arranged in ahierarchy using the slash character(/) as a separator, much like thepath in a URL. So a temperaturesensor in your kitchen mightpublish to a topic likesensors/temperature/home/kitchen.

See: Zoetrope

36 / 44

That's all for now.. 

Enough talkingLet's get our hands dirty!!

37 / 44

Project #2 

13 12 11 10

9 8 7 6 5 4 3 2

L

5V A0

ANALOG IN

AREF

1

GND

TXRX

RESET

3V3

A1

A2

A3

A4

A5

VIN

GND

GND

DIGITAL (PWM= )

Arduino TM

IOREF

ICSP

ICSP2

ON

POWER

01TX

0

RX0RESET

11

55

1010

1515

2020

2525

3030

A A

B B

C C

D D

E E

F F

G G

H H

I I

J J

13 12 11 ETH 9 8 7 6 5

SDCS

3 2 01TX RXAR

EF GND

5V A0

ANALOG IN

TX

RX

RESET

3V3

A1

A2

A3

A4

A5

VIN

GND

GND

DIGITAL (PWM SPI )

SCL SDA

<

IOREF

ICSP

CS

< <

Previous Circuit + Ethernet Shield38 / 44

39 / 44

Additional SWChecklist:

mosquitto messagebroker

MQTTLens ChromeExt./App

pubsubclient lib@knolleary

ARE

FGND

RESE

T3V

3L

TXRX

USB

EXT

PWR

SEL

PWR

ICSP

TX RX

31

21

11

01

9 8DIGITAL

7 6 5 4 3 2 1 0

1

5V GndPOWER

www.adruino.cc

ANALOG INVin 0 1 2 3 4 5

ADRUINO

Arduino - Sensor NodePublish data to the topic sensors/led/status every 2 seconds.

These values are the actual device state with considering localinput to the sensors (potentio and push button)

The data consist of a status (either "ON" or "OFF") and of anintensity (any integer ranging 0 - 254) in the following JSONformat:

{ "data": { "status": "ON", "intensity": 200 }}

40 / 44

MQTTLens - Client NodeSubscribe to the topic sensors/led/status.

41 / 44

Refs

42 / 44

Refs1. Arduino - Official Site | Tutorials2. Guide - Getting Started | Windows3. Tutorials - WebClient | WebClientRepeating | EthernetBegin4. Playground - WebClient POST5. MQTT and CoAP, IoT Protocols6. A Brief, but Practical Introduction to the MQTT Protocol and its Application to

IoT | Zoetrope7. Earthshine Design, Arduino Starter Kit Manual: A Complete Beginners Guide to

the Arduino

43 / 44

ENDEueung Mulyana

http://eueung.github.io/ET3010/arduinoET-3010 | Attribution-ShareAlike CC BY-SA

44 / 44

top related