Anda di halaman 1dari 95

Copyright

Arduino Uno: A Hands-On Guide for Beginner


Agus Kurniawan
1st Edition, 2015
Copyright © 2015 Agus Kurniawan
Table of Contents
Copyright
Preface
1. Preparing Development Environment
1.1 Arduino Uno
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 Uno
2.1 Getting Started
2.2 Installing Arduino Software
2.3 Connecting Arduino Uno board to Computer
2.4 Hello Arduino Uno: Blinking LED
2.5 Updating Program
3. Writing and Reading Digital Data
3.1 Getting Started
3.2 Wiring
3.3 Writing a Program
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
Source Code
Contact
Preface


This book was written to help anyone want to get started with Arduino Uno board
development. It describes the basic elements of Arduino Uno development using Arduino
software.


Agus Kurniawan
Depok, December 2015
1. Preparing Development Environment
1.1 Arduino Uno
Arduino/Genuino Uno is a microcontroller board based on the ATmega328P . It has 14
digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16
MHz quartz crystal, a USB connection, a power jack, an ICSP header and a reset button.
The following is a list of forms of Arduino Uno board.

The following is the board specification:

Microcontroller ATmega328P
Operating Voltage 5V
Input Voltage (recommended) 7-12V
Input Voltage (limit) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
PWM Digital I/O Pins 6
Analog Input Pins 6
DC Current per I/O Pin 20 mA
DC Current for 3.3V Pin 50 mA
Flash Memory 32 KB (ATmega328P)
of which 0.5 KB used by bootloader
SRAM 2 KB (ATmega328P)
EEPROM 1 KB (ATmega328P)
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 Uno. 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 Uno board, 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 Uno 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 Uno

This chapter explains how to work on setting up Arduino Uno board.


2.1 Getting Started
In this chapter, we set up Arduino Uno 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 Uno board too. You can download Arduino software
from https://www.arduino.cc/en/Main/Software. I recommend to use Arduino 1.6.5 or
later.
After downloaded, install Arduino software.Now you can open Arduino IDE.

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

If you’re working on Windows platform, you can see Arduino Uno detect on Device
Manager.
In Mac platform, this board usually is recognized as /dev/cu.usbmodem1421.
2.4 Hello Arduino Uno: Blinking LED
In this section, we build a blinking LED program using Blink program from Arduino
software. Arduino Uno 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 Uno board into your computer. Then, select board target by
clicking menu Tools -> Board and select Arduino/Genuino Uno.
Select serial port for your Arduino Uno board, for instance COM6 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 Uno 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 Uno
board.
3.1 Getting Started
To write a digital data on Arduino Uno board, we can use digitalWrite() and use
digitalRead() to read data from a digital output. To use Arduino Uno digital I/O pins, we
must define them using pinMode() with passing OUTPUT or INPUT parameter.
The following is a scheme of Arduino Uno board pinouts for digital Input/Output.

In this chapter, we build a program to illustrate how Arduino Uno 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 Uno. 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 Uno 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 Uno board.
4.1 Getting Started
Arduino Uno 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 Uno board.
The following is Arduino Uno pinout.

In this chapter, we try to access Arduino Uno 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 Uno 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 Uno.
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 Uno.
Read section 2.4 to upload the program.
After clicked Verify and Upload icons, you can see serial port for Arduino Uno 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 Uno, you can use UART pins on other digital pins. We can communicate with
Arduino Uno 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 Uno
pin 10 as RX and 11 as TX.

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

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


UART/Serial tool Rx is connected to Arduino Uno Digital Pin 11
UART/Serial tool GND is connected to Arduino Uno 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 Uno 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 Uno Analog I/O.
5.1 Getting Started
Arduino Uno board provides Analog I/O which can be connected to sensor or actuator
devices. Arduino Uno has PWM on digital pins: 3, 5, 6, 9, 10, and 11. See the following
of Arduino Uno Analog Iinput which is represented A0.. A5.

In this chapter, we try to access Arduino Uno 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 Uno 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 Uno digital pin 9


RGB LED pin 2 is connected to Arduino Uno 3.3V (VCC +3.3V)
RGB LED pin 3 (green) is connected to Arduino Uno digital pin 10
RGB LED pin 4 (blue) is connected to Arduino Uno digital pin 11

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

5.2.2 Writing Program


To display a certain color, we must combine colors from red, green, blue. Arduino Uno
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.
5.3 Demo Analog Input: Working with Potentiometer
In this section, we learn how to read analog input on Arduino Uno 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 Uno 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 Uno
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 Uno board on 3V3 pin (VCC +3.3V). Vout to Arduino
Uno board Analog input A0. In addition, GND to Arduino Uno 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 Uno board 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). You
can see I2C pins on Arduino Uno board, 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 Uno board.
6.2 Writing Program
We use PCF8591 AD/DA Converter as I2C source. You can connect PCF8591 AD/DA
Converter to Arduino Uno board directly.
The following is our wiring lab:

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

Hardware implementation can be shown in Figure below.


6.3 Writing Program
We use I2C on Arduino Uno 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();
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 Uno board board.
If done, open Serial monitor tool and connect to Arduino Uno 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 Uno 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 in Arduino Uno 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)

You can see these SPI pins on Arduino Uno board, shown in Figure below.

We can only use one SPI on Arduino Uno 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. This means you
connect pin 12 to pin 11 using cable.
The following is a sample of wiring.
7.3 Writing a Program
Firstly, we write a program for Arduino Uno. 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 Uno 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 Uno.
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 Uno. 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);

// 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!!");
}

void loop() {

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

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

Serial.print("IP Address: ");
Serial.println(Ethernet.localIP());

void loop() {

}
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.
Source Code

You can download source code on


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

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


blog: http://blog.aguskurniawan.net

Anda mungkin juga menyukai