Sie sind auf Seite 1von 125

Copyright

Arduino and Genuino MKR1000 Development Workshop


Agus Kurniawan
1st Edition, 2016
Copyright 2016 Agus Kurniawan


Table of Contents
Copyright
Preface
1. Setting up Development Environment
1.1 Arduino and Genuino MKR1000
1.2 Electronic Components
1.2.1 Arduino Starter Kit
1.2.2 Fritzing
1.2.3 Cooking-Hacks: Arduino Starter Kit
1.2.4 Arduino Sidekick Basic kit
1.3 Unboxing
1.4 Testing
2. Sketch Programming
2.1 Getting Started
2.2 Arduino Hardware Driver
2.3 Setting up Arduino and Genuino MKR1000 on Arduino
Sketch
2.4 Hello World for Arduino and Genuino MKR1000
2.5 Basic Sketch Programming
2.6 Digital I/O
2.7 Serial Communication
2.8 Analog I/O
2.9 PWM
2.9.1 Arduino/Genuino MKR1000 PWM
2.9.2 Controlling RGB LED Color
2.9.3 Arduino Implementation
2.10 Whats Next?
3. Working with SPI
3.1 Getting Started
3.2 Wiring
3.3 Writing a Program
3.4 Testing
4. Working with I2C
4.1 Getting Started
4.2 Writing Program
4.3 Writing Program
4.4 Testing
5. Arduino WiFi Networking
5.1 Getting Started
5.2 Adding WiFi101 Library
5.3 Scanning WiFi Hotspot
5.4 Connecting to a WiFi Network
5.5 Building a Simple IoT Application
5.5.1 Wiring
5.5.2 Writing Program
5.5.3 Testing
5.6 Updating WiFi101 Firmware
6. Working with Internal RTC and Sleep Mode
6.1 Getting Started
6.2 Adding RTC Library
6.3 Demo: Simple RTC
6.4 Demo: Connecting to Network Time Protocol (NTP)
Server
6.5 Demo: Sleep and Wake up
7. Controlling Arduino through Firmata Protocol
7.1 Getting Started
7.2 Installing Firmata Firmware
7.3 Demo
7.3.1 Wiring
7.3.2 Firmata Program on Arduino Board
7.3.3 Writing Python Program
7.3.4 Testing
8. Working with Firmata Protocol over WiFi
8.1 Getting Started
8.2 Demo: Wiring
8.3 Configuring Arduino Board for StandardFirmataWiFi
8.4 Writing Program
8.5 Testing
9. Arduino Cloud
9.1 Getting Started
9.2 Adding MQTT Library
9.3 Setting up Arduino Cloud
9.4 Writing Program
9.5 Testing
9.6 Publishing and Subscribing
9.7 Whats Next?
Source Code
Contact
Preface

This book was written to help anyone want to get started with Arduino/Genuino
MKR1000 development. It describes the basic elements of the development of
Arduino/Genuino MKR1000.

Agus Kurniawan
Berlin, April 2016
1. Setting up Development Environment
1.1 Arduino and Genuino MKR1000
Arduino is an open-source electronics prototyping platform based on flexible, easy-to-use
hardware and software. This board uses Atmel microcontroller series. There are many
Arduino hardware models that you can use. Further information about Arduino products,
you can visit on website http://arduino.cc/en/ .
Arduino MKR1000 has been designed to offer a practical and cost effective solution for
makers seeking to add Wi-Fi connectivity to their projects with minimal previous
experience in networking.

You can buy this product on your local electronic store. You also can order it by online.
Find it on http://arduino.cc/en/Main/Buy. You also can find this board on its distributor.
1.2 Electronic Components
We need electronic components to build our testing, for instance, Resistor, LED, sensor
devices and etc. I recommend you can buy electronic component kit.

1.2.1 Arduino Starter Kit


Store website: http://arduino.cc/en/Main/ArduinoStarterKit

1.2.2 Fritzing
Store website: http://shop.fritzing.org/ .
You can buy Fritzing Starter Kit with Arduino UNO or Fritzing Starter Kit with Arduino
Mega.
1.2.3 Cooking-Hacks: Arduino Starter Kit
Store website: http://www.cooking-hacks.com/index.php/shop/arduino/starter-
kits/arduino-starter-kit.html
1.2.4 Arduino Sidekick Basic kit
Store website: http://www.seeedstudio.com/depot/arduino-sidekick-basic-kit-p-775.html
Alternative online store
http://www.amazon.com/Arduino-Sidekick-Basic-Kit-Version/dp/B007B14HM8/
http://www.exp-tech.de/Zubehoer/Arduino-Sidekick-Basic-Kit.html
1.3 Unboxing
Since I live outside USA, I could bought Genuino MKR1000 from http://arduino.cc. The
following is the package.

After opened, I get Genuino MKR1000 board with pin headers.


1.4 Testing
For testing, I used Genuino MKR1000 on Windows, Mac and Ubuntu machines.

I also used Arduino Sidekick Basic kit for electronic components. I have some another
electronics kit.
2. Sketch Programming

This chapter explains how to work with Arduino/Genuino MKR1000 development using
Sketch.
2.1 Getting Started
The Arduino integrated development environment (IDE) is a cross-platform application
written in Java, and derives from the IDE for the Processing programming language and
the Wiring projects. A program or code written for Arduino is called a sketch.
To develop application based on Arduino board, we need Arduino software. You can
obtain it on http://arduino.cc/en/Main/Software . Please install based on your platform. To
develop Arduino and Genuino MKR1000, you must install Arduino 1.6.8 or later.
2.2 Arduino Hardware Driver
On OSX and Linux platforms, you dont need install any driver. OSX has already
recognized your Arduino board. You can verify it on Terminal.
ls /dev/cu*

You should serial port information of Arduino board on Terminal, for instance, I have
detected Arduino board on /dev/cu.usbmodem1411.

Sometimes it has problems due to Virtual USB to seria. You can download and install it
from http://www.ftdichip.com/Drivers/VCP.htm .
For Windows platform, you should install the driver. When you set up Arduino/Genuino
MKR1000, the driver will be installed too. Please follow steps on section 2.3 before
connecting Arduino/Genuino MKR1000 board into Windows PC.
2.3 Setting up Arduino and Genuino MKR1000 on Arduino
Sketch
To set up Arduino software for Arduino/Genuino MKR1000, we should install SAMD
Boards. You can click menu Tools -> Board -> Boards Manager..

After that, you should get a dialog. Find Arduino SAMD Boards, shown in Figure below.
Select it and then click Install button.
If done, you should Arduino/Genuino MKR1000 on board list from Arduino software.

Now youre ready to develop programs for Arduino/Genuino MKR1000.


2.4 Hello World for Arduino and Genuino MKR1000
Now youre ready to get started. For illustration, I use the sample code from Arduino,
Blink. You can visit on http://arduino.cc/en/Tutorial/Blink for configuration. By default,
Arduino/Genuino MKR1000 board has been attached a LED on digital pin 6.
On Arduino software, Click File -> Examples -> 01.Basics -> Blink.

Then you should see a sample code of Blink app. Change LED pin from 13 to 6
because Arduino/Genuino MKR1000 has on-board LED on pin 6.
Now try to connect your Arduino into computer.
On Arduino software, we select our Arduino board by clicking menu Tools-> Board and
select Arduino MKR1000.
We also select a serial port from attached Arduino board on your mach machine. Click
menu Tools -> Port. Then, select a serial port which Arduino/Genuino MKR1000 is
attached.
Now you can compile and upload Blink app to Arduino board. See Compile and Upload
icons.
After compiled and uploaded, you should get messages on status panel. A sample of
uploaded message can be seen in Figure below.
You also should see the LED will be on/off every second.
2.5 Basic Sketch Programming
To develop a program for Arduino using Sketch, you should have a basic programming for
Sketch. Basically, Sketch language is C/C++ programming language. Some functions
already have been defined for Sketch so we can call them on our program. Further
information about Skecth programming language, please read on this
site, https://www.arduino.cc/en/Reference/HomePage .
2.6 Digital I/O
In this section, we try to build Arduino program by utilizing digital I/O. We can write
digital data using digitalWrite(). To read digital input, you can use digitalRead().
The following is pinout of Arduino/Genuino MKR1000. Notice White panel which is
guided by a red arrow.

To implement our demo, you need a pushbutton and a LED. Connect LED to Arduino
digital pin 8. You also attach a pushbutton on Arduino digital pin 6.
Open Arduino software and write this code.
int led = 6;
int pushButton = 7;
int state = 0;

void setup() {
pinMode(led, OUTPUT);
pinMode(pushButton, INPUT);
}

void loop() {
state = digitalRead(pushButton);
digitalWrite(led,state);
delay(300);
}

Save this code, called ButtonLed.ino.


Compile and upload the program. After that, press pushbutton so you should lighting
LED.
2.7 Serial Communication
Arduino/Genuino MKR1000 has one UART which is represented as RX (digital pins 0)
and TX (digital pins 1). Its used for communication between the Arduino board and a
computer or other devices.
To access UART on Arduino board, we can use Serial
object, https://www.arduino.cc/en/Reference/Serial .
int led = 6;

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}

void loop() {
Serial.println("LED: HIGH");
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
Serial.println("LED: LOW");
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

Save this code, called SerialDemo.ino.


Compile and upload the program. To see program output, open Serial Monitor tool. Click
menu Tools -> Serial Monitor.

After clicked, you should see the program output.


2.8 Analog I/O
Arduino/Genuino MKR1000 has one DAC on pin DAC0 which located on pin A0.
Otherwise, the board has ADC on pin A0, A1, A2, A3, A4, A5, A6. Arduino/Genuino
MKR1000 has DAC resolution max 10-bit and ADC 12-bit.

In this section, we build a simple loopback app for DAC and ADC. You connect
DAC(A0) pin to A2. The following is my implementation.

Now we create Sketch program. In this case, we use 8-bit for Analog I/O. We can use
analogWriteResolution() and analogReadResolution(). To write Analog data, we can call
analogWrite() and call analogRead() for reading Analog data.
Write this sketch program.
int led = 6;
int val = 100;

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);

}

void loop() {

digitalWrite(led, HIGH); // turn the LED on



analogWriteResolution(8);
analogReadResolution(8);
Serial.print("Write DAC: ");
Serial.println(val);
analogWrite(DAC0,val);
int readADC = analogRead(A2);
Serial.print("Read ADC: ");
Serial.println(readADC);

delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off
delay(1000); // wait for a second

val++;
if(val > 110) {
val = 100;
}

}

Save this program as AnalogDemo.


Compile and run the program. After that, open Serial Monitor to see program output. The
following is a sample of program output:
2.9 PWM
In this scenario we build a Sketch application to control RGB LED color using Arduino
Analog output (PWM). RGB LED has 4 pins that you can see it on Figure below.

To understand these pins, you can see the following Figure.

Note:

Pin 1: Red
Pin 2: Common pin
Pin 3: Green
Pin 4: Blue

Now we can start to build a Sketch application and hardware implementation.

2.9.1 Arduino/Genuino MKR1000 PWM


Please be careful if you want to work with Arduino PWM. You should see PWM label so
you obtain PWM pins easily on Arduino/Genuino MKR1000 It writes DIGITAL (PWM
~). It means your PWM pins can be found on DIGITAL pins which pin with ~, for
instance, ~2,~3,~4,~5.
You can see PWM pins on picture below (see red arrow).

2.9.2 Controlling RGB LED Color


Firstly we implement RGB LED hardware. The following is a hardware schema.
For our testing, we configure the following PWM pins.

RGB LED pin 1 (red) is connected to Arduino PWM pin 5


RGB LED pin 2 is connected to Arduino VCC +3.3V
RGB LED pin 3 (green) is connected to Arduino PWM pin 4
RGB LED pin 4 (blue) is connected to Arduino PWM pin 3

Here is a sample implementation with Arduino/Genuino MKR1000.


2.9.3 Arduino Implementation
Now we implement our RGB LED controller in Arduino. We can define RGB LED pins
for Arduino/Genuino MKR1000.
int redPin = 5;
int greenPin = 4;
int bluePin = 3;

Now we initialize pins on setup().


void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(9600);
}

We define a function, called setColor(). This function aims to write RGB values on PWM
pins.
void setColor(int red, int green, int blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

Now we control RGB values on RGB LED, for instance, Red, Green, Blue, Yellow,
Purple, Aqua.
void loop()
{
setColor(255, 0, 0); // red
Serial.println("red");
delay(1000);
setColor(0, 255, 0); // green
Serial.println("green");
delay(1000);
setColor(0, 0, 255); // blue
Serial.println("blue");
delay(1000);
setColor(255, 255, 0); // yellow
Serial.println("yellow");
delay(1000);
setColor(80, 0, 80); // purple
Serial.println("purple");
delay(1000);
setColor(0, 255, 255); // aqua
Serial.println("aqua");
delay(1000);
}

Save this code, called test_rgb_arduino.ino.


Compile and verify this code. If success, you can upload it to Arduino board.
If success, you can see RGB LED blinking with different colors. Here is a sample output
of RGB LED with Genuino MKR1000.
You also see output on Serial Monitor.
2.10 Whats Next?
To get more practices, I recommend you to try several sensor and actuactor devices to be
attached on Arduino/Genuino MKR1000 board. There are many sensor kits that you can
buy on local electronics store or online store such as eBay,
Banggood, http://www.banggood.com/37-In-1-Sensor-Module-Board-Set-Kit-For-
Arduino-p-89734.html .
3. Working with SPI

In this chapter Im going to explain how to work with SPI on Arduino/Genuino MKR1000
board.
3.1 Getting Started
The Serial Peripheral Interface (SPI) is a communication bus that is used to interface one
or more slave peripheral integrated circuits (ICs) to a single master SPI device; usually a
microcontroller or microprocessor of some sort.
SPI in Arduino/Genuino MKR1000 board can be defined on the following pins:

MOSI on DOUT pin (Digital pin 8)


MISO on DIN pin (Digital pin 10)
SCLK on SCK (Digital pin 9)

We can only use one SPI on Arduino/Genuino MKR1000 board with SPI master mode.
We develop program based SPI using SPI
library, https://www.arduino.cc/en/Reference/SPI .
In this chapter, we build a SPI Loopback app. Lets start!.
3.2 Wiring
To develop SPI loopback, we can connect MOSI pin to MISO pin. This means you
connect pin 8 to pin 10 using cable.
The following is a sample of wiring.
3.3 Writing a Program
Firstly, we write a program for Arduino/Genuino MKR1000. Write these codes on
Arduino IDE.
#include <SPI.h>

byte sendData,recvData;
void setup() {
SPI.begin();
Serial.begin(9600);
randomSeed(80);
}

void loop() {
sendData = random(50, 100);
recvData = SPI.transfer(sendData);

Serial.print("Send=");
Serial.println(sendData,DEC);
Serial.print("Recv=");
Serial.println(recvData,DEC);
delay(800);
}

Save this code as SPIDemo.


3.4 Testing
Now you can upload program to Arduino/Genuino MKR1000 board. If done, open Serial
Monitor tool from Arduino. You should see received data from SPI.
4. Working with I2C

In this chapter we learn how to work with I2C on Arduino/Genuino MKR1000 board
using Arduino program.
4.1 Getting Started
The I2C (Inter-Integrated Circuit) bus was designed by Philips in the early 80s to allow
easy communication between components which reside on the same circuit board. TWI
stands for Two Wire Interface and for most marts this bus is identical to IC. The name
TWI was introduced by Atmel and other companies to avoid conflicts with trademark
issues related to IC.
I2C bus consists of two wires, SDA (Serial Data Line) and SCL (Serial Clock Line).
Arduino/Genuino MKR1000 has I2C pins on digital 12 (SCL) and 11 (SDA).

For testing, I used PCF8591 AD/DA Converter module with sensor and actuator devices.
You can find it on the following online store:

Amazon, http://www.amazon.com/PCF8591-Converter-Module-Digital-
Conversion/dp/B00BXX4UWC/
eBay, http://www.ebay.com
Dealextreme, http://www.dx.com/p/pcf8591-ad-da-analog-to-digital-digital-to-
analog-converter-module-w-dupont-cable-deep-blue-336384
Aliexpress, http://www.aliexpress.com/

In addition, you can find this device on your local electronics store/online store.
This module has mini form model too, for instance, you can find it on Amazon,
http://www.amazon.com/WaveShare-PCF8591T-Converter-Evaluation-
Development/dp/B00KM6X2OI/ .

This module use PCF8591 IC and you can read the datasheet on the following URLs.

http://www.electrodragon.com/w/images/e/ed/PCF8591.pdf
http://www.nxp.com/documents/data_sheet/PCF8591.pdf
In this chapter, we build a program to access sensor via I2C using Arduino software
on Arduino/Genuino MKR1000 board.
4.2 Writing Program
We use PCF8591 AD/DA Converter as I2C source. You can connect PCF8591 AD/DA
Converter to Arduino/Genuino MKR1000 board directly.
The following is our wiring lab:

PCF8591 AD/DA Converter SDA > Arduino/Genuino MKR1000 SDA (pin digital
11)
PCF8591 AD/DA Converter SCL > Arduino/Genuino MKR1000 CLK0 (pin
digital 12)
PCF8591 AD/DA Converter VCC > Arduino/Genuino MKR1000 VCC 3.3V
(+3.3V)
PCF8591 AD/DA Converter GND > Arduino/Genuino MKR1000 GND

Hardware implementation can be shown in Figure below.


4.3 Writing Program
We use I2C on Arduino/Genuino MKR1000 board using Wire library like Arduino
way. PCF8591 AD/DA Converter module has three sensor devices: Thermistor, Photo-
voltaic cell and Potentiometer. This module runs on I2C bus with address 0x90. In this
case, we read all sensor data.
Open Arduino IDE and write this code.
#include "Wire.h"
#define PCF8591 (0x90 >> 1) // I2C bus address
#define PCF8591_ADC_CH0 0x00 // thermistor
#define PCF8591_ADC_CH1 0x01 // photo-voltaic cell
#define PCF8591_ADC_CH2 0x02
#define PCF8591_ADC_CH3 0x03 // potentiometer
byte ADC1, ADC2, ADC3;

void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop()
{
// read thermistor
Wire.beginTransmission(PCF8591);
Wire.write((byte)PCF8591_ADC_CH0);
Wire.endTransmission();
Wire.requestFrom(PCF8591, 2);
ADC1=Wire.read();
ADC1=Wire.read();

Serial.print("Thermistor=");
Serial.println(ADC1);

// read photo-voltaic cell
Wire.beginTransmission(PCF8591);
Wire.write(PCF8591_ADC_CH1);
Wire.endTransmission();
Wire.requestFrom(PCF8591, 2);
ADC2=Wire.read();
ADC2=Wire.read();

Serial.print("Photo-voltaic cell=");
Serial.println(ADC2);

// potentiometer
Wire.beginTransmission(PCF8591);
Wire.write(PCF8591_ADC_CH3);
Wire.endTransmission();
Wire.requestFrom(PCF8591, 2);
ADC3=Wire.read();
ADC3=Wire.read();

Serial.print("potentiometer=");
Serial.println(ADC3);

delay(500);
}

Save this code as I2CSensor.


4.4 Testing
Now you can upload and run the program to Arduino/Genuino MKR1000 board board.
If done, open Serial monitor tool and connect to Arduino/Genuino MKR1000 to see the
program output. The following is a sample output.
5. Arduino WiFi Networking

This chapter explains how to work with on-board WiFi on Arduino/Genuino MKR1000.
5.1 Getting Started
Arduino/Genuino MKR1000 has on-board WiFi on Arduino/Genuino MKR1000. You can
access it via WiFi101 library. Please visit it
on http://www.arduino.cc/en/Reference/WiFi101 .
In this section, we try to build programs for WiFi on Arduino/Genuino MKR1000
5.2 Adding WiFi101 Library
We can add WiFi101 library by clicking menu Sketch -> Include Library -> Manage
Libraries.

Then, you get a dialog. Type wifi on Search textbox so you should see WiFi101. Install
this library.
Now youre ready to use WiFi101 library.
5.3 Scanning WiFi Hotspot
The first demo is to scan WiFi around your environment. We use WiFi.scanNetworks() to
retrieve a list of SSID.
Write this program into Arduino Sketch.
#include <WiFi101.h>

int led = 6;

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}

void loop() {
digitalWrite(led, HIGH);
scanWiFi();
digitalWrite(led, LOW);
delay(15000);
}

void scanWiFi() {
Serial.print("Scanning");
byte ssid = WiFi.scanNetworks();

Serial.print("found ");
Serial.println(ssid);

for (int i = 0; i<ssid; i++) {
Serial.print(">> ");
Serial.print(WiFi.SSID(i));
Serial.print("\tRSSI: ");
Serial.print(WiFi.RSSI(i));
Serial.print(" dBm");
Serial.print("\tEncryption: ");
Serial.println(WiFi.encryptionType(i));
}
Serial.println("");
Serial.println("");
}

Save this program as WifiScan.


Compile and upload the program into Arduino MKR1000 board. After that, you can open
Serial Monitor to see a list of SSID.
A sample of program output can be seen in Figure below.
5.4 Connecting to a WiFi Network
The second demo is to connect a WiFi and then access external a website. We use a
sample program WiFiWebClient. You can find it by clicking menu File -> Examples ->
WiFi101 -> WiFiWebClient .
After that, you should see the program, shown in Figure below.

Modify values ssid and pass for SSID and SSIDs key.
Compile and upload the program into Arduino. Open Serial Monitor to see the message.
A sample of program output on Serial Monitor:
5.5 Building a Simple IoT Application
In this demo we build a simple IoT application. We use three LEDs. We define HTTP
request as follows:

http://<arduino_ip>/gpio1/1 turns on LED 1


http://<arduino_ip>/gpio1/0 turns off LED 1
http://<arduino_ip>/gpio2/1 turns on LED 2
http://<arduino_ip>/gpio2/0 turns off LED 2
http://<arduino_ip>/gpio3/1 turns on LED 3
http://<arduino_ip>/gpio3/0 turns off LED 3

Lets start.

5.5.1 Wiring
We use three LEDs to be attached on Arduino MKR1000.

The following is our wiring:

LED 1 is connected to digital pin 6


LED 1 is connected to digital pin 4
LED 1 is connected to digital pin 3

You can see my wiring in Figure below.


5.5.2 Writing Program
We modify WiFiWebClient to handle requests. Open Arduino Sketch and write this
program.
#include <WiFi101.h>

int led1 = 6;
int led2 = 4;
int led3 = 3;

const char* ssid = "ssid";


const char* password = "ssid_key";
int status = WL_IDLE_STATUS;

WiFiServer server(80);

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

// prepare GPIO5
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led3, 0);

// Connect to WiFi network
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, password);

// wait 10 seconds for connection:
delay(10000);
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server
server.begin();
Serial.println("Server started");

// Print the IP address


char ips[24];
IPAddress ip = WiFi.localIP();
sprintf(ips, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
Serial.println(ips);
}

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}

// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();

// Match the request
int val1 = 0;
int val2 = 0;
int val3 = 0;
int ledreq = 0;
if (req.indexOf("/gpio1/0") != -1) {
val1 = 0;
ledreq = 1;
}
else if (req.indexOf("/gpio1/1") != -1) {
val1 = 1;
ledreq = 1;
}
else if (req.indexOf("/gpio2/0") != -1) {
val2 = 0;
ledreq = 2;
}
else if (req.indexOf("/gpio2/1") != -1) {
val2 = 1;
req = 2;
}
else if (req.indexOf("/gpio3/0") != -1) {
val3 = 0;
ledreq = 3;
}
else if (req.indexOf("/gpio3/1") != -1) {
val3 = 1;
ledreq = 3;
}
else {
Serial.println("invalid request");
client.stop();
return;
}

// Set GPIO2 according to the request


digitalWrite(led1, val1);
digitalWrite(led2, val2);
digitalWrite(led3, val3);

client.flush();

// Prepare the response


String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML
if(ledreq==1) {
s += "LED1 is ";
s += (val1)? "ON": "OFF";
}else if(ledreq==2) {
s += "LED2 is ";
s += (val2)? "ON": "OFF";
}else if(ledreq==3) {
s += "LED3 is ";
s += (val3)? "ON": "OFF";
}
s += "</html>\n";

// Send the response to the client


client.print(s);
delay(1);
client.stop();
Serial.println("Client disonnected");

}
Save program as IoTDemo.

5.5.3 Testing
Compile and upload the program into Arduino board. Open Serial Monitor.
Wait it until you see IP Address of Arduino on Serial Monitor.

Open a browser. NNow you can try to turn on LED1 by navigating to


http://<arduino_ip>/gpio1/1 on your browse.
A response on Serial Monitor can be seen in Figure below.

You should see LED1 is ON too.


Now you can try to turn off LED1 by navigating to http://<arduino_ip>/gpio1/0 .

You should get a response as below. You also see LED1 is OFF.
5.6 Updating WiFi101 Firmware
If you get problems on WiFi module, you can update WiFi101 firmware. You can follow
the instructions on https://github.com/arduino-libraries/WiFi101-FirmwareUpdater .
6. Working with Internal RTC and Sleep Mode

This chapter explains how to work with RTC on Arduino/Genuino MKR1000.


6.1 Getting Started
Arduino/Genuino MKR1000 has built-in RTC module on the board so we can access it
from Sketch program using RTC library. Further information about this library, you can
read it on http://www.arduino.cc/en/Reference/RTC .
Lets start.
6.2 Adding RTC Library
Firstly, we add RTC library into Arduino software. Click menu Sketch -> Include Library
-> Manage Libraries.

You should get a dialog. Type rtc so you should see RTCZero. Install it.
6.3 Demo: Simple RTC
In RTCZero, we can set a time using setTime() and setDate() functions. Otherwise, we
read a time using the following functions

getYear()
getMonth()
getDay()
getHours()
getMinutes()
getSeconds()

For demo, we will set and read a time.


Write this program into Arduino software.
#include <RTCZero.h>

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

rtc.begin(); // initialize RTC

Serial.println("RTC set time");


// set the current time 29 Feb 2016 7:23 AM
rtc.setDate(29, 2, 16);
rtc.setTime(7, 23, 00);
delay(1000);

Serial.println("RTC Read time");


Serial.println("-------------------");
}

void loop() {
Serial.print("RTC, Time = ");
print2digits(rtc.getMinutes());
Serial.write(':');
print2digits(rtc.getHours());
Serial.write(':');
print2digits(rtc.getSeconds());
Serial.print(", Date (D/M/Y) = ");
Serial.print(rtc.getDay());
Serial.write('/');
Serial.print(rtc.getMonth());
Serial.write('/');
Serial.print(rtc.getYear());
Serial.println();
delay(1000);
}

void print2digits(int number) {


if (number >= 0 && number < 10) {
Serial.write('0');
}
Serial.print(number);
}

Save this program as RTCdemo.ino. Now you compile and upload the program.
To see the program output, you can open Serial Monitor tool.
6.4 Demo: Connecting to Network Time Protocol (NTP)
Server
Sometimes you wan to synch your current date & time with specific server. Its usually
use NTP protocol. This protocol is built ob UDP protocol. Further information about NTP
protocol, you can read it on https://en.wikipedia.org/wiki/Network_Time_Protocol .
In this section, we try to access time on time.nist.gov via NTP. We can use a program
sample from Arduino. You can click menu File -> Examples -> WiFi101 ->
WifiUdpNtpClient. After that, you should see program, shown in Figure below.
Compile and upload the program to Arduino board. Now you can open Serial Monitor to
see the program messages.
6.5 Demo: Sleep and Wake up
We can set Arduino/Genuino MKR1000 on sleep mode by calling stanbyMode() from
RTCZero object. To wake up the board, we call setAlarmTime() with passing a callback
function and enableAlarm().
For testing, we create a simple program which is starting on sleep mode on setup(). If the
board wakes up, the program on loop() will be executed.
Now open Arduino Sketch and write this program.
#include <RTCZero.h>

int led = 6;
RTCZero rtc;

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

pinMode(led, OUTPUT);
digitalWrite(led, LOW);

rtc.begin(); // initialize RTC

Serial.println("RTC set time");


// set the current time 29 Feb 2016 7:23 AM
rtc.setDate(29, 2, 16);
rtc.setTime(7, 23, 00);
delay(1000);

Serial.println("RTC Read time");


Serial.println("-------------------");
Serial.println("set standby");
rtc.setAlarmTime(7, 24, 00);
rtc.enableAlarm(rtc.MATCH_HHMMSS);
rtc.attachInterrupt(wakeup);
rtc.standbyMode();
}

void loop() {
// this program will be executed
// after program wakes up
Serial.println(">> do something");
delay(800);
}

void wakeup()
{
Serial.println("Wake up");
digitalWrite(led, HIGH);
}
The program will wake up one minute later. Save the program as RTCAlarm.
Compile and upload the program.
You should see the program output which is shown in Figure below.
After waked up, the program run codes on loop(). A sample of program output can be seen
in Figure below.
7. Controlling Arduino through Firmata Protocol

This chapter explains how to control Arduino/Genuino MKR1000 board from computer
using Firmata.
7.1 Getting Started
In this scenario we build a desktop application to control sensor/actuator devices on
Arduino board. Several methods can be used to implement this case. In this chapter, we
use Firmata protocol to access Arduino board from Computer. I use Python as example
which accesses Arduino board.
Further information about Firmata, please it
on http://firmata.org and https://github.com/firmata/protocol .
7.2 Installing Firmata Firmware
To implement Firmata on Arduino board, you should install Firmata program on Arduino.
You can get it by clicking menu File -> Examples -> Firmata -> StandardFirmata .

After that, you get program codes for Firmata.


Configure board and port for Arduino/Genuino MKR1000. Then, upload the program into
the board.
Now youre ready to develop Firmata program.
7.3 Demo
In this demo, we use three LEDs as actuator devices on Arduino. We will control these
LEDs from Python program.
Lets start.

7.3.1 Wiring
We connect three LEDs on Digital pin 6, 7 and 8 from Arduino/Genuino MKR1000.
The following is my wiring.

7.3.2 Firmata Program on Arduino Board


You can install Firmata on Arduino board. Please read section 7.2 to deploy Firmata on
Arduino board.

7.3.3 Writing Python Program


There are several options to use Firmata library for Python. In this section, I use
pyfirmata, https://github.com/tino/pyFirmata .
You can install pyfirmata via pip.
$ pip install pyfirmata

You also can install it from source code.


$ git clone https://github.com/tino/pyFirmata
$ cd pyFirmata
$ python setup.py install

After installed pyfirmata, you can write Python program as below.


from pyfirmata import Arduino
import time

board = Arduino('/dev/cu.usbmodem1411')
led1_pin = 6
led2_pin = 7
led3_pin = 8

def turn_off_all():
board.digital[led1_pin].write(0)
board.digital[led2_pin].write(0)
board.digital[led3_pin].write(0)

# turn on LED sequentially


try:
while 1:

print('LED1 is ON')
board.digital[led1_pin].write(1)
time.sleep(1)
turn_off_all()

print('LED2 is ON')
board.digital[led2_pin].write(1)
time.sleep(1)
turn_off_all()

print('LED3 is ON')
board.digital[led3_pin].write(1)
time.sleep(1)
turn_off_all()

except KeyboardInterrupt:
turn_off_all()

print("done")

Change serial port of Arduino/Genuino MKR1000.


Save this program into a file, called firmatademo.py.

7.3.4 Testing
To test the program, you can run Pyhon program from Terminal.
$ python firmatademo.py

If succeed, you should see three LEDs blinking respectively

You also see the program output, shown in Figure below.


8. Working with Firmata Protocol over WiFi

In this chapter Im going to explain how to control Arduino/Genuino MKR1000 via


Firmata protocol over WiFi.
8.1 Getting Started
On previous section, we already learn how to control Arduino board via Firmata protocol
over USB/serial port. Now we try a new feature of Firmata, called StandardFirmataWifi.
This program supports on the following board:

Arduino WiFi Shield (or clone)


Arduino WiFi Shield 101
Arduino MKR1000 board (built-in WiFi 101)
Adafruit HUZZAH CC3000 WiFi Shield

In this section, we try to control LED using Firmata protocol over WiFi. As we know,
Arduino/Genuino MKR1000 has built-iin WiFi. For client application, we use Node.js
app. Make sure you alredy done with chapter 5.
8.2 Demo: Wiring
We use the same components from chapter 8. Not all digital pins can be used while
implementing Firmata WiFi on Arduino/Genuino MKR1000 . Make sure it works.
The following is our wiring:

LED 1 is connected to digital pin 6


LED 1 is connected to digital pin 4
LED 1 is connected to digital pin 3

You can see my wiring in Figure below.


8.3 Configuring Arduino Board for StandardFirmataWiFi
Now we must install Firmata over WiFi program into Arduino board. From Arduino
software, you can click menu File -> Examples -> Firmata -> StandardFirmataWiFi .

After that, you can see two program: StandardFirmataWiFi and wifiConfig.h
To configure Firmata WiFi on Arduino/Genuino MKR1000, you can open wifiConfig.h.
Because we use Arduino/Genuino MKR1000, we uncomment on WIFI_101, see it in
Figure below.
Please remark/uncomment for these lines

#define ARDUINO_WIFI_SHIELD
#define HUZZAH_WIFI

The next step is to configure SSID target. You can set them on ssid variable. You can set
WiFi SSID on it.
After that, you configure WiFi security:

No security, you can uncomment: #define WIFI_NO_SECURITY


WPA security, you can uncomment #define WIFI_WPA_SECURITY and then set
WPA key (variable: wpa_passphrase)
WPA security, you can uncomment #define WIFI_WEP_SECURITY and then set
WEP key (variable: wep_key)

If done, save this program.


Now you can compile and upload this program into Arduino/Genuino MKR1000.
8.4 Writing Program
This section is to write Node.js program. Please install Node.js on your computer, please
check it on https://nodejs.org/ .
Now you can create a file, called package.json.
{
"name": "firmatawifi",
"description": "controlling Arduino via Firmata protocol over WiFi",
"version": "0.0.1",
"dependencies": {
"firmata": "latest",
"etherport-client": "latest"
}
}

Save it.
On Terminal, type this command on path where package.json is located.
$ npm install

Make sure your computer already connected to Internet.


If finished, we create program to turn on/off three LEDs.
Create a file, firmatawifi.js , and write this program.
var Firmata = require("firmata").Board;
var EtherPortClient = require("etherport-client").EtherPortClient;
var board = new Firmata(new EtherPortClient({
host: "192.168.1.189",
port: 3030
}));

board.on("ready", function() {
console.log("Connected to Arduino!");
console.log(
board.firmware.name + "-" +
board.firmware.version.major + "." +
board.firmware.version.minor
);

var led = 1;

this.pinMode(6, this.MODES.OUTPUT);
this.pinMode(4, this.MODES.OUTPUT);
this.pinMode(3, this.MODES.OUTPUT);

setInterval(function() {
this.digitalWrite(6, 0);
this.digitalWrite(4, 0);
this.digitalWrite(3, 0);

if(led==1) {
this.digitalWrite(6, 1);
console.log("LED 1 ON");
}
if(led==2) {
this.digitalWrite(4, 1);
console.log("LED 2 ON");
}
if(led==3) {
this.digitalWrite(3, 1);
console.log("LED 3 ON");
}

led++;
if(led>3)
led = 1;

}.bind(this), 3000);


});

Change value host with IP address of Arduino/Genuino MKR1000.


You can check it on your WiFi router. On Arduino/Genuino MKR1000 board, you can see
its MAC address so you match it on WiFi router.
8.5 Testing
Now you can test the program by typing this command on Terminal. Make sure that
Terminal has navigated to a path where firmatawifi.js file is located.
$ node firmatawifi.js

You should get response from the program.


A sample of program output:

You should see three blinking LEDs .


9. Arduino Cloud

In this chapter Im going to explain how to connect Arduino board to Arduino Cloud via
MQTT protocol.
9.1 Getting Started
Arduino Cloud is a new product from Arduino. Currently, this is still Beta version while
Im writing this book. You can check it on https://create.arduino.cc/iot/products/cloud/ .
In this section, we try to access Arduino Cloud from Arduino/Genuino MKR1000.
9.2 Adding MQTT Library
Firstly, we add MQTT to Arduino software. Clicking Sketch -> Include Library ->
Manage Libraries .

Then, you get a dialog. Type paho and you should see MQTT. Install this library.
Now youre ready to access Arduino Cloud.
9.3 Setting up Arduino Cloud
Now we setup our Arduino Cloud and connect Arduino/Genuino MKR1000 to Arduino
Cloud. Firstly, you have already registered on https://id.arduino.cc . After that, please log
in to that website.
Now navigate to https://cloud.arduino.cc/cloud/getting-started .

Click NEXT button. Then, select MKR1000 board.


Now we are asked to install MQTT. We have installed on section 9.2. Click NEXT button.

Fill your board name. If done, click NEXT button.


Now you can see your Arduino configuration.

Click NEXT button to generate the Arduino Sketch code.


Copy that program into Arduino.
9.4 Writing Program
You should modify program to fit with your environment. Change ssid, pass and Arduino
Cloud setting and credentials.
// Include libraries
#include <SPI.h>
#include <WiFi101.h>
#include <WiFiSSLClient.h>
#include <MQTTClient.h>

// Your local WiFi settings


const char ssid[] = "wlan"; // your network SSID (name)
const char pass[] = "wlan_key"; // your network WPA password

// Arduino Cloud settings and credentials


const char server[] = "mqtt.arduino.cc";
const char userName[] = "username";
const char deviceName[] = "devName";
const char deviceId[] = "devId";
const char devicePsw[] = "devPsw";

int ledPin = LED_BUILTIN; // pin to blink, use the built-in LED

WiFiSSLClient net; // SSL client to use for MQTT connection


MQTTClient client; // MQTT client

void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

pinMode(ledPin, OUTPUT); // set the LED pin mode

// check for the presence of the shield:


if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true); // don't continue
}

// attempt to connect to WiFi network:


Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);

while (WiFi.begin(ssid, pass) != WL_CONNECTED) {


// unsuccessful, retry in 4 seconds
Serial.print("failed ");
delay(4000);
Serial.print("retrying ");
}
// configure the MQTT client
client.begin(server, 8883, net);

// connect to the MQTT server


connect();
}

void connect() {
Serial.println("connecting");

// attempt to connect to the MQTT server


while (!client.connect(deviceName, deviceId, devicePsw)) {
// connection failed, print '.' and retry
Serial.print(".");
}

Serial.println("connected!");
}

void loop() {
// let the MQTT client process events
client.loop();

// publish an "on" message to the device's blink topic and turn the LED on
client.publish("/agusk/blackduck/blink", "on");
Serial.println("publishing on");
digitalWrite(ledPin, HIGH);
delay(1000);

// publish an "off" message to the device's blink topic and turn the LED off
client.publish("/agusk/blackduck/blink", "off");
Serial.println("publishing off");
digitalWrite(ledPin, LOW);
delay(1000);
}

// incoming message handler, print out the received message


void messageReceived(String topic, String payload, char * bytes, unsigned
Serial.print("incoming: ");
Serial.print(topic);
Serial.print(" - ");
Serial.print(payload);
Serial.println();
}

Please change /agusk/blackduck/blink with your config.


If youre lost your Arduino Cloud configuration, you can visit and login
on https://cloud.arduino.cc/cloud . Check your device name.
9.5 Testing
Now you can compile and upload program to Arduino/Genuino MKR1000. Open Serial
Monitor to see the message.
9.6 Publishing and Subscribing
The program on section 9.4 is publishing messages. Now you can subscribe by
calling client.subscribe(/agusk/blackduck/blink) on connect() function. Change
/agusk/blackduck/blink with your config.
// Include libraries
#include <SPI.h>
#include <WiFi101.h>
#include <WiFiSSLClient.h>
#include <MQTTClient.h>

// Your local WiFi settings


const char ssid[] = "wlan"; // your network SSID (name)
const char pass[] = "wlan_key"; // your network WPA password

// Arduino Cloud settings and credentials


const char server[] = "mqtt.arduino.cc";
const char userName[] = "username";
const char deviceName[] = "devName";
const char deviceId[] = "devId";
const char devicePsw[] = "devPsw";

int ledPin = LED_BUILTIN; // pin to blink, use the built-in LED

WiFiSSLClient net; // SSL client to use for MQTT connection


MQTTClient client; // MQTT client

void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

pinMode(ledPin, OUTPUT); // set the LED pin mode

// check for the presence of the shield:


if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true); // don't continue
}

// attempt to connect to WiFi network:


Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);

while (WiFi.begin(ssid, pass) != WL_CONNECTED) {


// unsuccessful, retry in 4 seconds
Serial.print("failed ");
delay(4000);
Serial.print("retrying ");
}

// configure the MQTT client


client.begin(server, 8883, net);

// connect to the MQTT server


connect();
}

void connect() {
Serial.println("connecting");

// attempt to connect to the MQTT server


while (!client.connect(deviceName, deviceId, devicePsw)) {
// connection failed, print '.' and retry
Serial.print(".");
}

Serial.println("connected!");
// subscribe
client.subscribe("/agusk/blackduck/blink");
}

void loop() {
// let the MQTT client process events
client.loop();

// publish an "on" message to the device's blink topic and turn the LED on
client.publish("/agusk/blackduck/blink", "on");
Serial.println("publishing on");
digitalWrite(ledPin, HIGH);
delay(1000);

// publish an "off" message to the device's blink topic and turn the LED off
client.publish("/agusk/blackduck/blink", "off");
Serial.println("publishing off");
digitalWrite(ledPin, LOW);
delay(1000);
}

// incoming message handler, print out the received message


void messageReceived(String topic, String payload, char * bytes, unsigned
Serial.print("incoming: ");
Serial.print(topic);
Serial.print(" - ");
Serial.print(payload);
Serial.println();
}

Compile and upload the program.


Open Serial Monitor and you should see publishing/subscribing messages.
9.7 Whats Next?
You can do more practices with several cloud development platforms such as Azure,
AWS, Google Cloud, etc. I have a plan to write e-book about Azure IoT with utilizing
some IoT devices.
Source Code

You can download source code on


http://www.aguskurniawan.net/book/mkr1000c1102.zip .
Contact

If you have question related to this book, please contact me at aguskur@hotmail.com . My


blog: http://blog.aguskurniawan.net

Das könnte Ihnen auch gefallen