Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
455 views

Ebook Arduino Leonardo

eBook Arduino Leonardo

Uploaded by

Toni Junihartono
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
455 views

Ebook Arduino Leonardo

eBook Arduino Leonardo

Uploaded by

Toni Junihartono
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

Copyright

Arduino Leonardo and Arduino Micro: A Hands-On Guide for Beginner


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

** Arduino Leonardo and Arduino/Genuino Micro are a copyright and a trademark


from https://www.arduino.cc
Table of Contents
Copyright
Preface
1. Preparing Development Environment
1.1 Arduino Leonardo and Arduino Micro
1.2 Electronics 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 v2
1.2.5 Grove - Starter Kit for Arduino
1.2.6 DFRobot - Arduino Kit for Beginner v3
1.3 Development Tools
1.4 Testing
2. Setting Up Arduino Leonardo and Arduino Micro
2.1 Getting Started
2.2 Installing Arduino Software
2.3 Connecting Arduino Leonardo/Micro board to Computer
2.4 Hello Arduino Leonardo/Micro: Blinking LED
2.5 Updating Program
3. Writing and Reading Digital Data
3.1 Getting Started
3.2 Wiring
3.4 Testing
4. Serial Communication (UART)
4.1 Getting Started
4.2 Hello UART
4.2.1 Wiring
4.2.2 Writing a Program
4.2.3 Testing
4.3 Working with SoftwareSerial
5. PWM and Analog Input
5.1 Getting Started
5.2 Demo Analog Output (PWM) : RGB LED
5.2.1 Wiring
5.2.2 Writing Program
5.2.3 Testing
5.3 Demo Analog Input: Working with Potentiometer
5.3.1 Wiring
5.3.2 Writing Program
5.3.3 Testing
6. Working with I2C
6.1 Getting Started
6.2 Writing Program
6.3 Writing Program
6.4 Testing
7. Working with SPI
7.1 Getting Started
7.2 Wiring
7.3 Writing a Program
7.4 Testing
8. Accessing EEPROM
8.1 Getting Started
8.2 EEPROM Demo
9. Arduino Networking
9.1 Getting Started
9.2 Arduino Ethernet Shield
9.3 Demo 1 : Getting IP Address from DHCP Server
9.3.1 Writing Program
9.3.2 Testing
9.4 Demo 2: Building Web Server
9.4.1 Writing Program
9.4.2 Testing
10. Keyboard and Mouse HID
10.1 Getting Started
10.2 Keyboard Demo
10.3 Mouse Demo
Source Code
Contact
Preface


This book was written to help anyone want to get started with Arduino Leonardo and
Arduino/Genuino Micro boards development. It describes the basic elements of Arduino
Leonardo and Micro development using Arduino software.


Agus Kurniawan
Depok, January 2016
1. Preparing Development Environment
1.1 Arduino Leonardo and Arduino Micro
The Arduino/Genuino Micro is a microcontroller board based on the ATmega32U4
(datasheet). It has 20 digital input/output pins (of which 7 can be used as PWM outputs
and 12 as analog inputs), a 16 MHz crystal oscillator, a micro USB connection, an ICSP
header, and a reset button. It contains everything needed to support the microcontroller;
simply connect it to a computer with a micro USB cable to get started. It has a form factor
that enables it to be easily placed on a breadboard.
The Micro board is similar to the Arduino Leonardo in that the ATmega32U4 has built-in
USB communication, eliminating the need for a secondary processor. This allows the
Arduino/Genuino Micro to appear to a connected computer as a mouse and keyboard, in
addition to a virtual (CDC) serial / COM port.
The following is a form of Arduino Leonardo board.

The following is a form of Arduino Micro board.


The following is the board specification:

Microcontroller: ATmega32u4
Operating Voltage: 5V
Input Voltage (recommended)L: 7-12V
Input Voltage (limits): 6-20V
Digital I/O Pins: 20
PWM Channels: 7
Analog Input Channels: 12
DC Current per I/O Pin: 40 mA
DC Current for 3.3V Pin: 50 mA
Flash Memory: 32 KB (ATmega32u4) of which 4 KB used by bootloader
SRAM: 2.5 KB (ATmega32u4)
EEPROM: 1 KB (ATmega32u4)
Clock Speed: 16 MHz

Officially you can buy this board on https://store.arduino.cc. You can also buy these
products on the following stores:

SparkFun, https://www.sparkfun.com/
Adafruit, https://www.adafruit.com
Exp-Tech, http://www.exp-tech.de
Amazon, http://www.amazon.com
e-Bay, http://www.ebay.com
You also can buy this product on your local electronic store.
1.2 Electronics 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. We can use
electronics kit from Arduino to be developed on Arduino board. The following is a list of
electronics kit which can be used in our case.

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 v2
Store website: http://www.seeedstudio.com/depot/Sidekick-Basic-Kit-for-Arduino-V2-p-
1858.html
You also can find this kit on this online store.
http://www.exp-tech.de/seeed-studio-sidekick-basic-kit-for-arduino-v2
1.2.5 Grove - Starter Kit for Arduino
Another option, you can buy this kit on Seeedstudio,
http://www.seeedstudio.com/depot/Grove-Starter-Kit-for-Arduino-p-1855.html .

1.2.6 DFRobot - Arduino Kit for Beginner v3


DFRobot provides Arduino kit too. You can buy it on the following website.
http://www.dfrobot.com/index.php?route=product/product&path=35_49&product_id=345
1.3 Development Tools
To develop app with Arduino/Genuino Leonardo and Micro boards, I use Arduino IDE for
text editor. You can learn how to install it on chapter 2.
1.4 Testing
For testing, I used Arduino Leonardo on Windows 10, OS X and Ubuntu.
I also used Arduino Sidekick Basic kit for electronic components and several sensor
devices.
2. Setting Up Arduino Leonardo and Arduino Micro

This chapter explains how to work on setting up Arduino Leonardo/Micro board.


2.1 Getting Started
In this chapter, we set up Arduino Leonardo and Micro board development using Arduino
software. Then, try to build a simple Arduino app, Blinking.
Let’s start.
2.2 Installing Arduino Software
If you have experience in Arduino development, you can use Arduino IDE to develop
Arduino Leonardo board too. You can download Arduino software
from https://www.arduino.cc/en/Main/Software. I recommend to use Arduino 1.6.6 or
later.
After downloaded, install Arduino software.Now you can open Arduino IDE.

Click menu Tools -> Board . You should see Arduino Leonardo and Arduino/Genuino
Micro boards in the list.
2.3 Connecting Arduino Leonardo/Micro board to
Computer
Now you can connect Arduino Leonardo/Micro board into a computer via USB cable.

If you’re working on Windows platform, you can see Arduino Leonardo/Micro detect on
Device Manager. A sample of output from Device Manager (Windows) which detected my
Arduino Micro.
For Arduino Leonardo, it is detected as COM10 on my Windows.
In Mac platform, this board usually is recognized as /dev/cu.usbmodem1421.
2.4 Hello Arduino Leonardo/Micro: Blinking LED
In this section, we build a blinking LED program using Blink program from Arduino
software. Arduino Leonardo/Micro board provides onboard LED which is connected on
pin 13. We use this LED for our demo.
Let’s start to write our Blink program. In this demo, I use Arduino 1.6.6.
Open Arduino. Click menu File -> Examples -> 01.Basics -> Blink.

Then, you can see Blink source code as follows.


Firstly, connect your Arduino Leonardo/Micro board into your computer. Then, select
board target by clicking menu Tools -> Board and select Arduino/Genuino
Leonardo/Micro.
Select serial port for your Arduino Leonardo/Micro board, for instance COM5 in
Windows platform.
To upload the program, you can click Verify icon and then click Upload icon.
After uploaded, you can see onboard LED is blinking.
A sample output of blinking program can be seen in Figure below.
2.5 Updating Program
If you have modified the program and want to upload to Arduino Leonardo/Micro board,
you compile and upload the program too.
3. Writing and Reading Digital Data

In this chapter I’m going to explain how to work with digital input/output on Arduino
Leonardo/Micro board.
3.1 Getting Started
To write a digital data on Arduino Leonardo board, we can use digitalWrite() and use
digitalRead() to read data from a digital output. To use Arduino Leonardo digital I/O pins,
we must define them using pinMode() with passing OUTPUT or INPUT parameter.
The following is a scheme of Arduino Leonardo board pinouts for digital Input/Output.

The following is a scheme of Arduino Micro board pinouts for digital Input/Output.
In this chapter, we build a program to illustrate how Arduino Leonardo/Micro digital
input/output work. We need a LED and a pushbutton.
Let’s start!.
3.2 Wiring
We use built-in LED which is attached on pin 13 Arduino Leonardo/Micro. Then, we
connect a pushbutton to pin 3 The following is a sample of wiring.

3.3 Writing a Program


To create a program, we just open Arduino IDE and write this code.
int led = 13;
int pushButton = 3;
int state = 0;

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

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

Save these codes as ButtonLed.


3.4 Testing
Now you can upload and run this program to Arduino Leonardo/Micro board. For testing,
try to press pushbutton. You should see a lighting LED on the board.
4. Serial Communication (UART)

In this chapter I’m going to explain how to access UART on Arduino Leonardo/Micro
board.
4.1 Getting Started
Arduino Leonardo/Micro provides UART which can be accessed via Serial library or
SoftwareSerial. Further information about Serial object, you can read it
on https://www.arduino.cc/en/Reference/Serial . We can call Serial.read() to read one byte
from UART and Serial.write() to write one byte into UART.
UART is represented as RX and TX pins. You can see UART pins on Arduino Leonardo
board. Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data
using the ATmega32U4 hardware serial capability. Note that on the Micro, the Serial class
refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class.
The following is Arduino Leonardo and Arduino/Genuino Micro pinout.
In this chapter, we try to access Arduino Leonardo UART via serial adapter which is used
to upload a program too.
Let’s start!.
4.2 Hello UART
In this section, we try to use UART on Arduino Leonardo board.

4.2.1 Wiring
In this scenario, we use the same wiring from chapter 3. We will show pressed state from
push button on Serial.

4.2.2 Writing a Program


To use Serial object, we need to initialize it by calling Serial.begin(baudrate). In this case,
we can user baudrate 9600 on Arduino Leonardo or Micro.
Open Arduino software and write this program.
int led = 13;
int pushButton = 3;
int state = 0;

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

void loop() {
state = digitalRead(pushButton);
digitalWrite(led,state);
Serial.print("State=");
Serial.println(state);
delay(300);
}
Save this program as SerialDemo.

4.2.3 Testing
Now you can upload and run program. Don’t forget to set board target with Arduino
Leonardo/Micro. Read section 2.4 to upload the program.
After clicked Verify and Upload icons, you can see serial port for Arduino
Leonardo/Micro board on your computer. To see the UART output, open Serial Monitor
tool from Arduino IDE.
Set baud 9600 and Both NL & CR.

You should see the UART output on this window. A sample output can seen in Figure
above.
4.3 Working with SoftwareSerial
On Arduino Leonardo/Micro, you can use UART pins on other digital pins. We can
communicate with Arduino Leonardo/Micro board from computer via UART using
SoftwareSerial. In this scenario, we need Serial hardware. The following is a list of UART
tool you can use for this demo.

SparkFun FTDI Basic Breakout - 3.3V, https://www.sparkfun.com/products/9873


FTDI Cable 5V VCC-3.3V I/O, https://www.sparkfun.com/products/9717
Foca, http://imall.itead.cc/foca.html

In this scenario, I use Foca tool from iTead. We connect UART/Serial tool to Arduino
Leonardo/Micro pin 10 as RX and 11 as TX.

Consider we use Arduino Leonardo board. The following is our wiring:

UART/Serial tool Tx is connected to Arduino Leonardo/Micro Digital Pin 10


UART/Serial tool Rx is connected to Arduino Leonardo/Micro Digital Pin 11
UART/Serial tool GND is connected to Arduino Leonardo/Micro GND

A sample of hardware implementation can be seen in Figure below.


After connected to computer, it’s recognized as serial port, for instance, in my Windows, it
is detected as COM3.
Now you can open Arduino IDE and write these codes.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

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

mySerial.begin(9600);
}

void loop() {
if (mySerial.available()) {
Serial.write(mySerial.read());
}
if (Serial.available()) {
mySerial.write(Serial.read());
}

}

Save this program as CommSerial.


Compile and upload the program to Arduino Board board. If done, you can open Serial
Monitor tool.
On computer which is attached with UART/Serial too, run your serial application, for
instance, I use CoolTerm, http://freeware.the-meiers.org . Instal and run this app. Now you
can connect UART/Serial USB tool to your computer.
Configure your Serial application to connect UART/Serial USB. Select Arduino Leonardo
port and Baudrate 9600.
On Terminal menu, checked Local Echo, shown in Figure below.
If done, click OK button.
After connected, you can type words on this tool.
If done, you should them on Serial Monitor tool from Arduino. A sample output for Serial
Monitor and Serial application.
5. PWM and Analog Input

This chapter explains how to work with Arduino Leonardo/Micro Analog I/O.
5.1 Getting Started
Arduio Leonardo board provides Analog I/O which can be connected to sensor or actuator
devices. Arduino Leonardo/Micro has PWM on digital pins: 3, 5, 6, 9, 10, and 11. See the
following of Arduino Leonardo/Micro Analog input which is represented A0.. A5.
In this chapter, we try to access Arduino Leonardo/Micro Analog I/O using Arduino
software. There are two scenarios for our cases:

Controlling RGB LED


Reading Analog input using Potentiometer

Let’s start.
5.2 Demo Analog Output (PWM) : RGB LED
In this scenario we build a program to control RGB LED color using Arduino
Leonardo/Micro 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 program and hardware implementation.

5.2.1 Wiring
For our testing, we configure the following PWM pins.

RGB LED pin 1 (red) is connected to Arduino Leonardo/Micro digital pin 9


RGB LED pin 2 is connected to Arduino Leonardo/Micro 5V (VCC +5V)
RGB LED pin 3 (green) is connected to Arduino Leonardo/Micro digital pin 10
RGB LED pin 4 (blue) is connected to Arduino Leonardo/Micro digital pin 11

Here is a sample implementation with Arduino Micro and RGB Led.

5.2.2 Writing Program


To display a certain color, we must combine colors from red, green, blue. Arduino
Leonardo/Micro provides API for PWM like Arduino API such as analogWrite() and
analogRead() with analog value from 0 to 255.
Let’s start to build a program. Firstly, open Arduino Software. Then, write these scripts.
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

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

void loop()
{
setColor(0, 255, 255); // red
Serial.println("red");
delay(1000);
setColor(255, 0, 255); // green
Serial.println("green");
delay(1000);
setColor(255, 255, 0); // blue
Serial.println("blue");
delay(1000);
setColor(0, 0, 255); // yellow
Serial.println("yellow");
delay(1000);
setColor(80, 255, 80); // purple
Serial.println("purple");
delay(1000);
setColor(255, 0, 0); // aqua
Serial.println("aqua");
delay(1000);
}

void setColor(int red, int green, int blue)


{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
Save this program as PWMDemo.
This program will generate six colors: red, green, blue, yellow, purple, and aqua.

5.2.3 Testing
Upload and run the program. You should see several color on RGB LED.
The following is a sample demo on RGB LED.
If you open Serial Monitor, you should see program output.
5.3 Demo Analog Input: Working with Potentiometer
In this section, we learn how to read analog input on Arduino Leonardo and Micro board.
For illustration, I use Potentiometer as analog input source. Our scenario is to read analog
value from Potentiometer. Then, display it on Serial Monitor.
Arduino Leonardo/Micro has Analog inputs on A0..A5. If you want to work with many
analog inputs, you must expand it using ICs based ADC. In this section, we are working
on Arduino Leonardo/Micro Analog inputs.
Let’s start!.

5.3.1 Wiring
To understand Potentiometer, you see its scheme in Figure below.

You can connect VCC to Arduino Leonardo board on 3V3 pin (VCC +3.3V). Vout
to Arduino Leonardo/Micro board Analog input A0. In addition, GND to Arduino
Leonardo/Micro board GND. The following is hardware implementation. I use slide
potentiometer.
5.3.2 Writing Program
Firstly, create a program using Arduino IDE. To read analog input, we can use
analogRead() function. Ok, Let’s write these scripts.
int val = 0;

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

void loop() {
val = analogRead(A0);
Serial.print("ADC=");
Serial.println(val);
delay(300);
}
Save this code as ADCDemo.

5.3.3 Testing
Upload and run this program. If success, you can see analog value using Serial Monitor
tool from Arduino IDE.
6. Working with I2C

In this chapter we learn how to work with I2C on Arduino Leonardo and Micro boards
using Arduino program.
6.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 Leonardo and Arduino/Genuino Micro have I2C on digital 2 pin (SDA) and
digital 3 pin (SCL).
You can see I2C pins on Arduino Leonardo and Micro boards, shown in Figure below.
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 Leonardo or Micro board.
6.2 Writing Program
We use PCF8591 AD/DA Converter as I2C source. You can connect PCF8591 AD/DA
Converter to Arduino Leonardo/Micro board directly.
The following is our wiring lab:

PCF8591 AD/DA Converter SDA —> Arduino Leonardo/Micro SDA (pin digital 2)
PCF8591 AD/DA Converter SCL —> Arduino Leonardo/Micro CLK (pin digital 3)
PCF8591 AD/DA Converter VCC —> Arduino Leonardo/Micro VCC 5V (+5V)
PCF8591 AD/DA Converter GND —> Arduino Leonardo/Micro GND

Hardware implementation can be shown in Figure below.


6.3 Writing Program
We use I2C on Arduino Leonardo and Micro boards 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();
ADC3=Wire.read();

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

delay(500);
}

Save this code as I2CSensor.


6.4 Testing
Now you can upload and run the program to Arduino Leonardo/Micro board.
If done, open Serial monitor tool and connect to Arduino Leonardo/Micro to see the
program output. The following is a sample output.
7. Working with SPI

In this chapter I’m going to explain how to work with SPI on Arduino Leonardo/Micro
board.
7.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 pins are not connected to any of the digital I/O pins as they are on the Uno, they are
only available on the ICSP connector and on the nearby pins labelled MISO, MOSI and
SCK.
You can see these SPI pins on Arduino Leonardo and Micro board, shown in Figure
below.
We can only use one SPI on Arduino Leonardo 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!.
7.2 Wiring
To develop SPI loopback, we can connect MOSI pin to MISO pin. If you use Arduino
Leonardo, you find MOSI and MISO pins on ICSP connector. For Arduino/Genuino
Micro, you can connect MOSI pin to MISO pin which their label name are shown.
The following is a sample of wiring for Arduino Micro.
7.3 Writing a Program
Firstly, we write a program for Arduino Leonardo/Micro. 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.
7.4 Testing
Now you can upload program to Arduino Leonardo/Micro board. If done, open Serial
Monitor tool from Arduino. You should see received data from SPI.
8. Accessing EEPROM

In this chapter I’m going to explain how to work with EEPROM in Arduino
Leonardo/Micro.
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 .
8.2 EEPROM Demo
In this section, we try to access EEPROM on Arduino Leonardo/Micro. 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 <EEPROM.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);
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(2000);

}

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. If you don’t see anything in Serial
Monitor, try to reset your Arduino board by pressing Reset button on the board.
A sample of program output can be seen in Figure below.
9. Arduino Networking

In this chapter I’m going to explain how to connect Arduino board to a network.
9.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 boards into a
network.
9.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, Arduino Leonardo and Ethernet shield.
9.3 Demo 1 : Getting IP Address from DHCP Server
The first demo is to build app to read a local IP Address. In this scenario, you should
connect Arduino Ethernet shield to a network with installed DHCP server so Arduino
board will obtain IP address.
We use Ethernet library to access Ethernet shield. You can read it
on https://www.arduino.cc/en/Reference/Ethernet .

9.3.1 Writing Program


We can use localIP() to retrieve a local IP address. Firstly, call Ethernet.begin() with
passing MAC address of Ethernet shield.
Now you can write this program to Arduino software.
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };

EthernetClient client;

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

if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
}

void loop() {
Serial.print("IP Address: ");
Serial.println(Ethernet.localIP());
delay(500);
}
Save the program as IPLocalDemo.

9.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.
9.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.

9.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, 0, 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
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();
}
}
Save the program as WebServer.

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

This program will refresh automatically.


A sample of program output on Serial Monitor tool.
10. Keyboard and Mouse HID

In this chapter I’m going to explain how to work with Keyboard and Mouse HID in
Arduino Leonardo and Micro.
10.1 Getting Started
Arduino provides keyboard and mouse API which our program can interact with
Keyboard and Mouse HID. Further information about this library, please read it
on https://www.arduino.cc/en/Reference/MouseKeyboard .
In this chapter, we learn how to access Keyboard and Mouse HID.
10.2 Keyboard Demo
The first demo is to build a program which interacts with Keyboard on computer, We use a
pushbutton to activate our Keyboard. While a pushbutton is pressed, we send a character
to Keyboard. We use Keyboard.write() to write a character.
We use the same wiring from chapter 3. Connect your pushbutton on digital pin 3.
Let’s write this program in Arduino IDE.
#include "Keyboard.h"

int pushButton = 3;
int led = 13;
int state = 0;
byte chr = 50;

void setup() {
pinMode(pushButton, INPUT);
// initialize control over the keyboard:
Keyboard.begin();
}

void loop() {
state = digitalRead(pushButton);
digitalWrite(led,state);
if (state==HIGH) {
// Type the next ASCII value from what you received:
Keyboard.write(chr);
chr = chr + 1;
if(chr>80)
chr = 50;
}
delay(300);
}
Save this program as KeyboardDemo.
Now you can compile and deploy the program into the board.
After that, run text editor, for instance Notepad on Windows platform.
Now you can press a pushbutton. Then, you should see some characters on your a text
editor.
A sample of text editor can be seen in Figure below.
10.3 Mouse Demo
The second demo is to build a program to access Mouse in a computer. We will move our
Mouse while pressing a pushbutton. We use a pushbutton which is attached on digital pin
3. We use Mouse.move() to move Mouse position.
Now you can write the following program on Arduino IDE.
#include "Mouse.h"

int pushButton = 3;
int led = 13;
int state = 0;

void setup() {
pinMode(pushButton, INPUT);
Mouse.begin();
}

void loop() {
state = digitalRead(pushButton);
digitalWrite(led,state);
if (state==HIGH) {
Mouse.move(10, 10, 0);
}
delay(300);
}
Save the program as MouseDemo.
Now you can compile and upload the program into the board.
After that, try to press a pushbutton so your Mouse position is changing.
Source Code

You can download source code on


http://www.aguskurniawan.net/book/leomicro18012016.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