You are on page 1of 102

Copyright

Arduino and Genuino 101 Development Workshop


Agus Kurniawan
1st Edition, 2016
Copyright © 2016 Agus Kurniawan

www.TechnicalBooksPDF.com
Table of Contents
Copyright
Preface
1. Setting up Development Environment
1.1 Arduino and Genuino 101
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 101 on Arduino
Sketch
2.4 Hello World for Arduino and Genuino 101
2.5 Basic Sketch Programming
2.6 Digital I/O
2.7 Serial Communication
2.8 Analog I/O

www.TechnicalBooksPDF.com
2.8.1 Arduino 101 Analog output (PWM)
2.8.2 Controlling RGB LED Color
2.8.3 Arduino Implementation
2.9 What’s 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. BLE Programming
5.1 Getting Started
5.2 Demo: BLE
6. Working with Accelerator and Gyroscope
6.1 Getting Started
6.2 Accelerator and Gyroscope Demo
7. Working with RTC
7.1 Getting Started
7.2 Demo: RTC
www.TechnicalBooksPDF.com
8. Accessing EEPROM
8.1 Getting Started
8.2 EEPROM Demo
9. Working with Arduino Firmata
9.1 Getting Started
9.2 Installing Firmata Firmware
9.3 Demo
9.3.1 Wiring
9.3.2 Firmata Program on Arduino Board
9.3.3 Writing Python Program
9.3.4 Testing
10. Arduino Networking
10.1 Getting Started
10.2 Arduino Ethernet Shield
10.3 Demo 1 : Accessing External Website
10.3.1 Writing Program
10.3.2 Testing
10.4 Demo 2: Building Web Server
10.4.1 Writing Program
10.4.2 Testing
What’s Next?
Source Code
Contact
www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
Preface

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

Agus Kurniawan
Berlin, March 2016

www.TechnicalBooksPDF.com
1. Setting up Development Environment

www.TechnicalBooksPDF.com
1.1 Arduino and Genuino 101
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 and Genuino 101 have some features in common with both UNO (connectors,
available peripherals) and Zero (32bit microcontroller, 3.3V IO) but the low power Intel
microcontroller, on-board BLE and motion sensors make it unique.

www.TechnicalBooksPDF.com
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. The following is the list of Arduino store you
can buy

Arduino store, http://store.arduino.cc/


Amazon, http://www.amazon.com
Cooking-hacks, http://www.cooking-hacks.com/index.php/shop/arduino.html
RS Components, http://www.rs-components.com
Element 14, http://www.element14.com
EXP-Tech, http://www.exp-tech.de

www.TechnicalBooksPDF.com
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.

www.TechnicalBooksPDF.com
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

www.TechnicalBooksPDF.com
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

www.TechnicalBooksPDF.com
1.3 Unboxing
Since I live outside USA, I could bought Genuino 101. The following is the package.

After opened, I get Genuino 101 board and a manual note.

www.TechnicalBooksPDF.com
1.4 Testing
For testing, I used Genuino 101 on Windows, Mac and Ubuntu machines.

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

www.TechnicalBooksPDF.com
2. Sketch Programming

This chapter explains how to work with Arduino/Genuino 101 development using Sketch.

www.TechnicalBooksPDF.com
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 101, you must install Arduino 1.6.7 or later.

www.TechnicalBooksPDF.com
2.2 Arduino Hardware Driver
On OSX and Linux platforms, you don’t 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.

For Windows platform, you should install the driver. When you set up Arduino/Genuino
101, the driver will be installed too. See section 2.3.

www.TechnicalBooksPDF.com
2.3 Setting up Arduino and Genuino 101 on Arduino Sketch
To set up Arduino software for Arduino/Genuino 101, we should install Intel Curie Board.
You can click menu Tools -> Board -> Boards Manager..

After that, you should get a dialog. Type “curie” on textbox so you should see Intel Curie
Boards, shown in Figure below.

www.TechnicalBooksPDF.com
Select it and then click Install button.
If done, you should Arduino 101 on board list from Arduino software.

www.TechnicalBooksPDF.com
Now you’re ready to develop programs for Arduino/Genuino 101.

www.TechnicalBooksPDF.com
2.4 Hello World for Arduino and Genuino 101
Now you’re 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 board has been attached a LED on digital pin 13.
On Arduino software, Click File -> Examples -> 01.Basics -> Blink.

Then you should see a sample code of Blink app.

www.TechnicalBooksPDF.com
Now try to connect your Arduino into computer.

www.TechnicalBooksPDF.com
On Arduino software, we select our Arduino board by clicking menu Tools-> Board and
select Arduino 101.

www.TechnicalBooksPDF.com
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 101 is attached.
Now you can compile and upload Blink app to Arduino board. See Compile and Upload
icons.

www.TechnicalBooksPDF.com
After compiled and uploaded, you should get messages as below.

www.TechnicalBooksPDF.com
You also should see the LED will be on/off every second.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
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 .

www.TechnicalBooksPDF.com
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().
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 = 8;
int pushButton =6;
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.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
2.7 Serial Communication
Arduino/Genuino 101 has one UART which is represented as RX (digital pins 0) and TX
(digital pins 1). It’s 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 = 13;

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.

www.TechnicalBooksPDF.com
After clicked, you should see the program output.

www.TechnicalBooksPDF.com
2.8 Analog I/O
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

www.TechnicalBooksPDF.com
Pin 3: Green
Pin 4: Blue

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

2.8.1 Arduino 101 Analog output (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 101 It writes DIGITAL (PWM ~). It
means your PWM pins can be found on DIGITAL pins which pin with ~, for instance,
~3,~5,~6,~9.
You can see PWM pins on picture below (see red arrow).

www.TechnicalBooksPDF.com
2.8.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 9


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

Here is a sample implementation with Arduino/Genuino 101.

www.TechnicalBooksPDF.com
2.8.3 Arduino Implementation
Now we implement our RGB LED controller in Arduino. We can define RGB LED pins
for Arduino/Genuino 101.
int redPin = 9;
int greenPin = 6;
int bluePin = 5;

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);

www.TechnicalBooksPDF.com
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 101.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
You also see output on Serial Monitor.

www.TechnicalBooksPDF.com
2.9 What’s Next?
To get more practices, I recommend you to try several sensor and actuactor devices to be
attached on Arduino/Genuino 101 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 .

www.TechnicalBooksPDF.com
3. Working with SPI

In this chapter I’m going to explain how to work with SPI on Arduino/Genuino 101 board.

www.TechnicalBooksPDF.com
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 101 board can be defined on the following pins:

MOSI on DOUT pin (Digital pin 11)


MISO on DIN pin (Digital pin 12)
SCLK on SCK (Digital pin 13)

We can only use one SPI on Arduino/Genuino 101 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. Let’s start!.

www.TechnicalBooksPDF.com
3.2 Wiring
To develop SPI loopback, we can connect MOSI pin to MISO pin. This means you
connect pin 12 to pin 11 using cable.
The following is a sample of wiring.

www.TechnicalBooksPDF.com
3.3 Writing a Program
Firstly, we write a program for Arduino/Genuino 101. Write these codes on Arduino IDE.
#include <SPI.h>

byte sendData,recvData;
void setup() {
SPI.begin();
Serial.begin(115200);

// source:
// http://forum.arduino.cc/index.php?topic=197633.0
byte randomDigit() {
unsigned long t = micros();
byte r = (t % 10) + 1;
for (byte i = 1; i <= 4; i++) {
t /= 10;
r *= ((t % 10) + 1);
r %= 11;
}
return (r - 1);
}

void loop() {
sendData = randomDigit();
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.

www.TechnicalBooksPDF.com
3.4 Testing
Now you can upload program to Arduino/Genuino 101 board. If done, open Serial
Monitor tool from Arduino. You should see received data from SPI.

www.TechnicalBooksPDF.com
4. Working with I2C

In this chapter we learn how to work with I2C on Arduino/Genuino 101 board using
Arduino program.

www.TechnicalBooksPDF.com
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 I²C. The name
TWI was introduced by Atmel and other companies to avoid conflicts with trademark
issues related to I²C.
I2C bus consists of two wires, SDA (Serial Data Line) and SCL (Serial Clock Line).
Arduino/Genuino 101 has I2C pins on A5 (SCL) and A4 (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/ .

www.TechnicalBooksPDF.com
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 101 board.

www.TechnicalBooksPDF.com
4.2 Writing Program
We use PCF8591 AD/DA Converter as I2C source. You can connect PCF8591 AD/DA
Converter to Arduino/Genuino 101 board directly.
The following is our wiring lab:

PCF8591 AD/DA Converter SDA —> Arduino/Genuino 101 SDA0 (pin A4)
PCF8591 AD/DA Converter SCL —> Arduino/Genuino 101 CLK0 (pin A5)
PCF8591 AD/DA Converter VCC —> Arduino/Genuino 101 VCC 3.3V (+3.3V)
PCF8591 AD/DA Converter GND —> Arduino/Genuino 101 GND

Hardware implementation can be shown in Figure below.

www.TechnicalBooksPDF.com
4.3 Writing Program
We use I2C on Arduino/Genuino 101 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(115200);
}
void loop()
{
// read thermistor
Wire.beginTransmission(PCF8591);
Wire.write(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();

www.TechnicalBooksPDF.com
ADC3=Wire.read();

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

delay(500);
}

Save this code as I2CSensor.

www.TechnicalBooksPDF.com
4.4 Testing
Now you can upload and run the program to Arduino/Genuino 101 board board.
If done, open Serial monitor tool and connect to Arduino/Genuino 101 to see the program
output. The following is a sample output.

www.TechnicalBooksPDF.com
5. BLE Programming

This chapter explains how to work with Bluetooth Low Energy on Arduino/Genuino 101.

www.TechnicalBooksPDF.com
5.1 Getting Started
Arduino/Genuino 101 provides BLE module into the booard. We use CurieBle to access
BLE module. In this section, we try to run a program sample from Arduino, called
BatteryMonitor.

www.TechnicalBooksPDF.com
5.2 Demo: BLE
We try a program sample, called BatteryMonitor. Click menu File -> Examples ->
CurieBle -> BatteryMonitor.

After clicked, you should codes, shown in Figure below.

www.TechnicalBooksPDF.com
This program will publish Battery information which read data on analog A5.
Battery service is defined
on https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx , as 0x180F.
#include <CurieBle.h>

BLEPeripheral blePeripheral;
BLEService batteryService("180F");

On setup() function, we initialize BLE service.


blePeripheral.setLocalName("BatteryMonitorSketch");
blePeripheral.setAdvertisedServiceUuid(batteryService.uuid()); // add the s
blePeripheral.addAttribute(batteryService); // Add the BLE Battery service
blePeripheral.addAttribute(batteryLevelChar); // add the battery level chara

www.TechnicalBooksPDF.com
batteryLevelChar.setValue(oldBatteryLevel); // initial value for battery

blePeripheral.begin();

On loop() function, we listen incoming BLE client. If connected, the program will
broadcast Battery information by calling updateBatteryLevel().
BLECentral central = blePeripheral.central();

// if a central is connected to peripheral:


if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
// turn on the LED to indicate the connection:
digitalWrite(13, HIGH);

// check the battery level every 200ms


// as long as the central is still connected:
while (central.connected()) {
long currentMillis = millis();
// if 200ms have passed, check the battery level:
if (currentMillis - previousMillis >= 200) {
previousMillis = currentMillis;
updateBatteryLevel();
}
}
// when the central disconnects, turn off the LED:
digitalWrite(13, LOW);
Serial.print("Disconnected from central: ");
Serial.println(central.address());
}

In updateBatteryLevel() function, we read analog A0 and then update Battery level by


calling setValue().
void updateBatteryLevel() {

int battery = analogRead(A0);


int batteryLevel = map(battery, 0, 1023, 0, 100);

if (batteryLevel != oldBatteryLevel) { // if the battery level has chan


Serial.print("Battery Level % is now: "); // print it
Serial.println(batteryLevel);
batteryLevelChar.setValue(batteryLevel); // and update the battery level
oldBatteryLevel = batteryLevel; // save the level for next compa
}
}

www.TechnicalBooksPDF.com
Now you can save the program. You can compile and upload the program.
If succeed, you can use BLE app on Android or iOS.
In this case, I use LightBlue on Mac.

After run LightBlue, you can see Battery service from Arduino/Genuino 101.

www.TechnicalBooksPDF.com
Click the service on LightBlue. Click Subscribe to get updated value from
Arduino/Genuino 101.

Then, you should see Battery information.

If you open Serial Monitor tool, you also see Battery level value.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
6. Working with Accelerator and Gyroscope

This chapter explains how to work with Accelerator and Gyroscope on Arduino/Genuino
101.

www.TechnicalBooksPDF.com
6.1 Getting Started
Arduino/Genuino 101 has built-in Accelerator and Gyroscope sensors. You can access it
via CuriIMU. In this chapter, we try to develop program for Accelerator and Gyroscope.

www.TechnicalBooksPDF.com
6.2 Accelerator and Gyroscope Demo
To access Accelerator and Gyroscope, we can call CurieIMU.begin(). We also set sensor
range using CurieIMU.setAccelerometerRange() and CurieIMU.setGyroRange()
functions.
Finally, we can get information about Accelerator and Gyroscope values using
CurieIMU.readAccelerometer() and CurieIMU.readGyro() functions.
Now open Arduino software and write this program.
#include <CurieIMU.h>

void setup() {
Serial.begin(9600); // initialize Serial communication
while (!Serial); // wait for the serial port to open

// initialize device
Serial.println("Initializing IMU device…");
CurieIMU.begin();

// Set the accelerometer range to 2G


CurieIMU.setAccelerometerRange(2);

// Set the accelerometer range to 250 degrees/second


CurieIMU.setGyroRange(250);
}

void loop() {
int axRaw, ayRaw, azRaw; // raw accelerometer values
float ax, ay, az;

int gxRaw, gyRaw, gzRaw; // raw gyro values


float gx, gy, gz;

// read raw accelerometer measurements from device


CurieIMU.readAccelerometer(axRaw, ayRaw, azRaw);

// convert the raw accelerometer data to G's


ax = convertRawAcceleration(axRaw);
ay = convertRawAcceleration(ayRaw);
az = convertRawAcceleration(azRaw);

// display tab-separated accelerometer x/y/z values


Serial.print("a:\t");
Serial.print(ax);
Serial.print("\t");
Serial.print(ay);
Serial.print("\t");
Serial.print(az);
Serial.println();

www.TechnicalBooksPDF.com
// read raw gyro measurements from device
CurieIMU.readGyro(gxRaw, gyRaw, gzRaw);

// convert the raw gyro data to degrees/second


gx = convertRawGyro(gxRaw);
gy = convertRawGyro(gyRaw);
gz = convertRawGyro(gzRaw);

// display tab-separated gyro x/y/z values


Serial.print("g:\t");
Serial.print(gx);
Serial.print("\t");
Serial.print(gy);
Serial.print("\t");
Serial.print(gz);
Serial.println();

// wait 5 seconds
delay(5000);
}

float convertRawAcceleration(int aRaw) {


// since we are using 2G range
// -2g maps to a raw value of -32768
// +2g maps to a raw value of 32767

float a = (aRaw * 2.0) / 32768.0;

return a;
}

float convertRawGyro(int gRaw) {


// since we are using 250 degrees/seconds range
// -250 maps to a raw value of -32768
// +250 maps to a raw value of 32767

float g = (gRaw * 250.0) / 32768.0;

return g;
}

Save it as AcceleratorGyroDemo.ino.

www.TechnicalBooksPDF.com
Now you compile and run the program.
Open Serial Monitor. Try to shake or move your Arduino/Genuino 101 so you should see
the sensor outputs.
A sample output program can be seen in Figure below.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
7. Working with RTC

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

www.TechnicalBooksPDF.com
7.1 Getting Started
Arduino/Genuino 101 has built-in RTC module on the board so we can access it from
Sketch program using CurieTime.
Let’s start.

www.TechnicalBooksPDF.com
7.2 Demo: RTC
In CurieTime, we can set a time using setTime() function. Otherwise, we read a time using
the following functions

year()
month()
day()
hour()
minute()
second()

For demo, we will set and read a time.


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

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

Serial.println("CurieTime set time");


// set the current time 29 Feb 2016 7:23 AM
setTime(7, 23, 00, 29, 02, 2016);
delay(1000);

Serial.println("CurieTime Read time");


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

void loop() {
Serial.print("RTC, Time = ");
print2digits(hour());
Serial.write(':');
print2digits(minute());
Serial.write(':');
print2digits(second());
Serial.print(", Date (D/M/Y) = ");
Serial.print(day());
Serial.write('/');
Serial.print(month());
Serial.write('/');
Serial.print(year());
Serial.println();
delay(1000);
}

void print2digits(int number) {

www.TechnicalBooksPDF.com
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.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
8. Accessing EEPROM

In this chapter I’m going to explain how to work with EEPROM in Arduino/Genuino 101.

www.TechnicalBooksPDF.com
8.1 Getting Started
EEPROM stands for Electrically Erasable Programmable Read-Only Memory and is a
type of non-volatile memory used in computers and other electronic devices to store small
amounts of data that must be saved when power is removed.
The supported micro-controllers on the various Arduino boards have different amounts of
EEPROM: 1024 bytes on the ATmega328, 512 bytes on the ATmega168 and ATmega8, 4
KB (4096 bytes) on the ATmega1280 and ATmega2560.
To access EEPROM on Arduino board, we can use EEPROM object. Further information
about EEPROM, you can read it on https://www.arduino.cc/en/Reference/EEPROM .

www.TechnicalBooksPDF.com
8.2 EEPROM Demo
In this section, we try to access EEPROM on Arduino/Genuino 101. To access EEPROM
on Arduino/Genuino 101, you need CurieEEPROM. Unfortunately, it doesn’t update on
Arduino software but you download it on https://github.com/01org/corelibs-
arduino101/releases .
Open Arduino software and check a path of Sketchbook location, shown in Figure below.

Extract file from https://github.com/01org/corelibs-arduino101/releases . Copy


CurieEEPROM from libraries folder into Sketchbook location folder. You can see it on the
Figure below.

www.TechnicalBooksPDF.com
Close and run again Arduino software. Let’s start to build a program.
In this demo, we do the following actions:

read EEPROM size using length()


write data into EEPROM using write()
read data from EEPROM using read()
clear all data on EEPROM using write() with value 0 on all EEPROM addresses

To achieve these actions, you can start to write program on Arduino software.
Write this program.
#include <CurieEEPROM.h>

byte value;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}

void loop() {
// get a size of EEPROM
Serial.print("EEPROM size: ");
Serial.print(EEPROM.length());
Serial.println(" bytes");

// write data into EEPROM on address 0, 5, 10


// value in byte = 0 .. 255
Serial.print("Writing EEPROM data…");
EEPROM.write(0, 30);
EEPROM.write(5, 135);
EEPROM.write(10, 211);

www.TechnicalBooksPDF.com
Serial.println("Done");

// read EEPROM on address 0, 5, 10


value = EEPROM.read(0);
Serial.print("value ADD 0 = ");
Serial.println(value);

value = EEPROM.read(5);
Serial.print("value ADD 5 = ");
Serial.println(value);

value = EEPROM.read(10);
Serial.print("value ADD 10 = ");
Serial.println(value);

// clear all EEPROM data


Serial.print("Clearing EEPROM data…");
for (int i = 0 ; i < EEPROM.length() ; i++) {
EEPROM.write(i, 0);
}
Serial.println("Done");

// turn the LED while finished


digitalWrite(13, HIGH);
Serial.println("Finished!!");

delay(5000);

www.TechnicalBooksPDF.com
Save this program as EEPROMDemo.
Now you can compile and upload the program into Arduino board. If done, open Serial
Monitor to see program output.
A sample of program output can be seen in Figure below.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
9. Working with Arduino Firmata

This chapter explains how to control Arduino/Genuino 101 board from computer using
Firmata.

www.TechnicalBooksPDF.com
9.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 .

www.TechnicalBooksPDF.com
9.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.

www.TechnicalBooksPDF.com
Configure board and port for Arduino 101. Then, upload the program into the board.
Now you’re ready to develop Firmata program.

www.TechnicalBooksPDF.com
9.3 Demo
In this demo, we use three LEDs as actuator devices on Arduino. We will control these
LEDs from Python program.
Let’s start.

9.3.1 Wiring
We connect three LEDs on Digital pin 10, 9 and 8 from Arduino/Genuino 101.
The following is my wiring.

9.3.2 Firmata Program on Arduino Board


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

9.3.3 Writing Python Program


There are several options to use Firmata library for Python. In this section, I use

www.TechnicalBooksPDF.com
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 = 10
led2_pin = 9
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:

www.TechnicalBooksPDF.com
turn_off_all()

print("done")

Change serial port of Arduino/Genuino 101.


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

9.3.4 Testing
To test the program, you can run Arduino server from Terminal.
$ python firmatademo.py

If succeed, you should see three LEDs blinking respectively

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

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
10. Arduino Networking

In this chapter I’m going to explain how to connect Arduino board to a network.

www.TechnicalBooksPDF.com
10.1 Getting Started
Mostly Arduino boards don’t provide a network module except Arduino Yun. If you want
to connect your Arduino board into a network, you should add a network module such as
Arduino Ethernet shield and WiFi shield.
In this chapter, we use Arduino Ethernet shield to connect our Arduino/Genuino 101
boards into a network.

www.TechnicalBooksPDF.com
10.2 Arduino Ethernet Shield
You can buy Arduino Ethernet shield on your local electronic store. You also buy it on
online stores.
I obtained Arduino Ethernet shield from eBay. The following is my Arduino Ethernet
shield.

This module fits on Arduino board. You can attach this module on the top of Arduino
board.
The following is my hardware configuration.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
10.3 Demo 1 : Accessing External Website
The first demo is to build app to access external website, for instance, www.google.com .
Make sure your network connected to Internet.
We use Ethernet library to access Ethernet shield. You can read it
on https://www.arduino.cc/en/Reference/Ethernet .

10.3.1 Writing Program


In this case, we sample program Arduino. You can reach it by clicking menu File ->
Examples -> Ethernet -> WebClient so you can get codes as follows.
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.


// Newer Ethernet shields have a MAC address printed on a sticker on the shiel
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
char server[] = "www.google.com"; // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign


IPAddress ip(192, 168, 1, 22);

// Initialize the Ethernet client library


// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

// start the Ethernet connection:


/*if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}*/
Ethernet.begin(mac, ip);

// give the Ethernet shield a second to initialize:


delay(1000);

www.TechnicalBooksPDF.com
Serial.println("connecting…");

// if you get a connection, report back via serial:


if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /search?q=arduino HTTP/1.1");
client.println("Host: www.google.com");
client.println("Connection: close");
client.println();
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}

void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}

// if the server's disconnected, stop the client:


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

// do nothing forevermore:
while (true);
}
}

Change value of ip for Arduino. In this code, I don’t use DHCP server so I remark codes
for DHCP case which I set static IP Address.

www.TechnicalBooksPDF.com
Save the program as WebClient.

10.3.2 Testing
Now you can compile and upload the program into Arduino board. Then, open Serial
Monitor to see the program output. Press Reset button on Arduino board to reset your
board.
A sample of program output is shown in Figure below.

www.TechnicalBooksPDF.com
www.TechnicalBooksPDF.com
10.4 Demo 2: Building Web Server
In this demo, we build a web server. This server will send a response with the current
Arduino input values.

10.4.1 Writing Program


We don”t write a program from a scratch. You can run the demo program by clicking
menu File -> Examples -> Ethernet -> Web Server.
Then, you obtain WebServer program. Modify IP address value.
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.


// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 22);

// Initialize the Ethernet server library


// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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

// start the Ethernet connection and the server:


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

void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line

www.TechnicalBooksPDF.com
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be clos
client.println("Refresh: 5"); // refresh the page automatically eve
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
Ethernet.maintain();
}
}

www.TechnicalBooksPDF.com
Save the program as WebServer.

10.4.2 Testing
Now you can compile and upload the program into Arduino board. Open Serial Monitor to
see the program output so you can see IP address of Arduino.
To test the program, open a browser and navigate to IP address of web server. Then, you
can see Analog input values on website.

www.TechnicalBooksPDF.com
In this case, my Arduino analog pins doesn’t connect to any sensor device so the output
value is 0.
This program will refresh automatically.
A sample of program output on Serial Monitor tool.

www.TechnicalBooksPDF.com
What’s Next?

Since Intel doesn’t release RTOS library for Intel Curie, I’ll continue to write RTOS
programming for Intel Curie on a new book.

www.TechnicalBooksPDF.com
Source Code

You can download source code on http://www.aguskurniawan.net/book/ar101ge.zip .


Contact

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


blog: http://blog.aguskurniawan.net

You might also like