You are on page 1of 229

Libraries

The Arduino environment can be


extended through the use of libraries,
just like most programming platforms.
Libraries provide extra functionality for
use in sketches, e.g. working with
hardware or manipulating data. A
number of libraries come installed with
the IDE, but you can also download or
create your own. See these
instructions for details on installing
libraries. There's also a tutorial on
writing your own libraries.
See the API Style Guide for information
on making a good Arduino-style API for
your library.
To use a library in a sketch, select it
from Sketch > Import Library.
Standard Libraries
EEPROM - reading and writing to
"permanent" storage
Ethernet - for connecting to the internet
using the Arduino Ethernet Shield
Firmata - for communicating with
applications on the computer using a
standard serial protocol.
GSM - for connecting to a GSM/GRPS
network with the GSM shield.
LiquidCrystal - for controlling liquid
crystal displays (LCDs)
SD - for reading and writing SD cards
Servo - for controlling servo motors
SPI - for communicating with devices
using the Serial Peripheral Interface
(SPI) Bus
SoftwareSerial - for serial
communication on any digital pins.
Version 1.0 and later of Arduino
incorporate Mikal
Hart'sNewSoftSerial library
as SoftwareSerial.
Stepper - for controlling stepper motors
TFT - for drawing text , images, and
shapes on the Arduino TFT screen
WiFi - for connecting to the internet
using the Arduino WiFi shield
Wire - Two Wire Interface (TWI/I2C) for
sending and receiving data over a net
of devices or sensors.

The Matrix and Sprite libraries are no


longer part of the core distribution.
Due Only Libraries
Audio - Play audio files from a SD card.
Scheduler - Manage multiple nonblocking tasks.
USBHost - Communicate with USB
peripherals like mice and keyboards.
Esplora Only Library
Esplora - this library enable you to
easily access to various sensors and
actuators mounted on the Esplora
board.
Arduino Robot Library
Robot - this library enables easy
access to the functions of the Arduino
Robot
Arduino Yn Bridge Library
Bridge Library - Enables
communication between the Linux
processor and the Arduino on the Yn.
USB Libraries (Leonardo, Micro, Due,
and Esplora)
Keyboard - Send keystrokes to an
attached computer.
Mouse - Control cursor movement on a
connected computer.
Contributed Libraries
If you're using one of these libraries,
you need to install it first. See these
instructions for details on installation.
There's also a tutorial on writing your
own libraries.
Communication (networking and
protocols):
Messenger - for processing text-based
messages from the computer
NewSoftSerial - an improved version of
the SoftwareSerial library
OneWire - control devices (from Dallas
Semiconductor) that use the One Wire
protocol.
PS2Keyboard - read characters from
a PS2 keyboard.
Simple Message System - send
messages between Arduino and the
computer
SSerial2Mobile - send text messages
or emails using a cell phone (via AT
commands over software serial)

Webduino - extensible web server


library (for use with the Arduino
Ethernet Shield)
X10 - Sending X10 signals over AC
power lines
XBee - for communicating
with XBees in API mode
SerialControl - Remote control other
Arduinos over a serial connection
Sensing:
Capacitive Sensing - turn two or more
pins into capacitive sensors
Debounce - for reading noisy digital
inputs (e.g. from buttons)
Displays and LEDs:
GFX - base class with standard
graphics routines (by Adafruit
Industries)
GLCD - graphics routines for LCD
based on the KS0108 or equivalent
chipset.
Improved LCD library fixes LCD
initialization bugs in official Arduino
LCD library
LedControl - for controlling LED
matrices or seven-segment displays
with a MAX7221 or MAX7219.
LedControl - an alternative to the Matrix
library for driving multiple LEDs with
Maxim chips.
LedDisplay - control of a HCMS29xx scrolling LED display.
Matrix - Basic LED Matrix display
manipulation library
PCD8544 - for the LCD controller on
Nokia 55100-like displays (by Adafruit
Industries)
Sprite - Basic image sprite
manipulation library for use in
animations with an LED matrix
ST7735 - for the LCD controller on a
1.8", 128x160 TFT screen (by Adafruit
Industries)
Audio and Waveforms:
FFT - frequency analysis of audio or
other analog signals
Tone - generate audio frequency
square waves in the background on
any microcontroller pin
Motors and PWM:

TLC5940 - 16 channel 12 bit PWM


controller.
Timing:
DateTime - a library for keeping track of
the current date and time in software.
Metro - help you time actions at regular
intervals
MsTimer2 - uses the timer 2 interrupt to
trigger an action every N milliseconds.
Utilities:
PString - a lightweight class for printing
to buffers
Streaming - a method to simplify print
statements

EEPROM Library

The microcontroller on the Arduino


board has EEPROM: memory whose
values are kept when the board is
turned off (like a tiny hard drive). This
library enables you to read and write
those bytes.
The microcontrollers 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.
Functions
read()
write()

read()
Description
Reads a byte from the EEPROM.
Locations that have never been written
to have the value of 255.
Syntax
EEPROM.read(address)
Parameters
address: the location to read from,
starting from 0 (int)
Returns
the value stored in that location (byte)
Example
#include <EEPROM.h>
int a = 0;
int value;
void setup()

{
Serial.begin(9600);
}
void loop()
{
value = EEPROM.read(a);
Serial.print(a);
Serial.print("\t");
Serial.print(value);
Serial.println();
a = a + 1;

making outgoing ones. The library supports


up to four concurrent connection (incoming
or outgoing or a combination).
Arduino communicates with the shield using
the SPI bus. This is on digital pins 11, 12,
and 13 on the Uno and pins 50, 51, and 52
on the Mega. On both boards, pin 10 is used
as SS. On the Mega, the hardware SS pin,
53, is not used to select the W5100, but it
must be kept as an output or the SPI
interface won't work.

if (a == 512)
a = 0;
delay(500);
}

write()
Description
Write a byte to the EEPROM.
Syntax
EEPROM.write(address, value)
Parameters
address: the location to write to,
starting from 0 (int)
value: the value to write, from 0 to 255
(byte)
Returns
none
Note
An EEPROM write takes 3.3 ms to
complete. The EEPROM memory has a
specified life of 100,000 write/erase
cycles, so you may need to be careful
about how often you write to it.
Example
#include <EEPROM.h>
void setup()
{
for (int i = 0; i < 255; i++)
EEPROM.write(i, i);
}
void loop()
{
}

Ethernet library
With the Arduino Ethernet Shield, this library
allows an Arduino board to connect to the
internet. It can serve as either a server
accepting incoming connections or a client

Ethernet class

The Ethernet class initializes the ethernet


library and network settings.

begin()
localIP()
maintain()

IPAddress class

The IPAddress class works with local and


remote IP addressing.
IPAddress()

Server class

The Server class creates servers which can


send data to and receive data from
connected clients (programs running on
other computers or devices).

Server
EthernetServer()
begin()
available()
write()
print()
println()
Client class

The client class creates clients that can


connect to servers and send and receive
data.

Client
EthernetClient()
if (EthernetClient)
connected()
connect()
write()
print()
println()
available()
read()
flush()
stop()
EthernetUDP class

The EthernetUDP class enables UDP


message to be sent and received.

begin()
read()
write()
beginPacket()
endPacket()
parsePacket()
available()
stop()
remoteIP()
remotePort()

Ethernet.begin()
Description
Initializes the ethernet library and
network settings.
With version 1.0, the library supports
DHCP. Using Ethernet.begin(mac) with
the proper network setup, the Ethernet
shield will automatically obtain an IP

address. This increases the sketch size


significantly.
Syntax
Ethernet.begin(mac);
Ethernet.begin(mac, ip);
Ethernet.begin(mac, ip, dns);
Ethernet.begin(mac, ip, dns, gateway);
Ethernet.begin(mac, ip, dns, gateway,
subnet);
Parameters
mac: the MAC (Media access control)
address for the device (array of 6
bytes). this is the Ethernet hardware
address of your shield. Newer Arduino
Ethernet Shields include a sticker with
the device's MAC address. For older
shields, choose your own.
ip: the IP address of the device (array
of 4 bytes)
dns: the IP address of the DNS server
(array of 4 bytes). optional: defaults to
the device IP address with the last
octet set to 1
gateway: the IP address of the network
gateway (array of 4 bytes). optional:
defaults to the device IP address with
the last octet set to 1
subnet: the subnet mask of the network
(array of 4 bytes). optional: defaults to
255.255.255.0
Returns
The DHCP version of this function,
Ethernet.begin(mac), returns an int: 1
on a successful DHCP connection, 0
on failure. The other versions don't
return anything.
Example
#include <SPI.h>
#include <Ethernet.h>
// the media access control (ethernet hardware)
address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
//the IP address for the shield:
byte ip[] = { 10, 0, 0, 177 };
void setup()
{
Ethernet.begin(mac, ip);
}
void loop () {}

Ethernet.localIP()
Description
Obtains the IP address of the Ethernet
shield. Useful when the address is auto
assigned through DHCP.
Syntax
Ethernet.localIP();
Parameters
none
Returns
the IP address
Example
#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 shield
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
// 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() {
// start the serial library:
Serial.begin(9600);
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet
using DHCP");
// no point in carrying on, so do nothing
forevermore:
for(;;)
;
}
// print your local IP address:
Serial.println(Ethernet.localIP());
}
void loop() {
}

Ethernet.maintain()
Description
Allows for the renewal of DHCP leases.
When assigned an IP address via
DHCP, ethernet devices are given a
lease on the address for an amount of
time. With Ethernet.maintain(), it is

possible to request a renewal from the


DHCP server. Depending on the
server's configuration, you may receive
the same address, a new one, or none
at all.
Ethernet.maintain() was added to
Arduino 1.0.1.
Syntax
Ethernet.maintain();
Parameters
none
Returns
byte:
0: nothing happened
1: renew failed
2: renew success
3: rebind fail
4: rebind success

IPAddress()
Description
Defines an IP address. It can be used
to declare both local and remote
addresses.
Syntax
IPAddress(address);
Parameters
address: a comma delimited list
representing the address (4 bytes, ex.
192, 168, 1, 1)
Returns
None
Example
#include <SPI.h>
#include <Ethernet.h>
// network configuration. dns server, gateway
and subnet are optional.
// the media access control (ethernet hardware)
address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
// the dns server ip
IPAddress dnServer(192, 168, 0, 1);
// the router's gateway address:
IPAddress gateway(192, 168, 0, 1);
// the subnet:
IPAddress subnet(255, 255, 255, 0);
//the IP address is dependent on your network
IPAddress ip(192, 168, 0, 2);

void setup() {
Serial.begin(9600);
// initialize the ethernet device
Ethernet.begin(mac, ip, dnServer, gateway, su
bnet);
//print out the IP address
Serial.print("IP = ");
Serial.println(Ethernet.localIP());
}
void loop() {
}

Server
Description
Server is the base class for all Ethernet
server based calls. It is not called
directly, but invoked whenever you use
a function that relies on it.

EthernetServer()
Description
Create a server that listens for
incoming connections on the specified
port.
Syntax
Server(port);
Parameters
port: the port to listen on (int)
Returns
None
Example
#include <SPI.h>
#include <Ethernet.h>
// network configuration. gateway and subnet
are optional.
// the media access control (ethernet hardware)
address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
//the IP address for the shield:
byte ip[] = { 10, 0, 0, 177 };
// the router's gateway address:
byte gateway[] = { 10, 0, 0, 1 };
// the subnet:
byte subnet[] = { 255, 255, 0, 0 };

// start listening for clients


server.begin();
}
void loop()
{
// if an incoming client connects, there will be
bytes available to read:
EthernetClient client = server.available();
if (client == true) {
// read bytes from the incoming client and
write them back
// to any clients connected to the server:
server.write(client.read());
}
}

begin()
Description
Tells the server to begin listening for
incoming connections.
Syntax
server.begin()
Parameters
None
Returns
None
Example
#include <SPI.h>
#include <Ethernet.h>
// the media access control (ethernet hardware)
address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
//the IP address for the shield:
byte ip[] = { 10, 0, 0, 177 };
// the router's gateway address:
byte gateway[] = { 10, 0, 0, 1 };
// the subnet:
byte subnet[] = { 255, 255, 0, 0 };
// telnet defaults to port 23
EthernetServer server = EthernetServer(23);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();

// telnet defaults to port 23


EthernetServer server = EthernetServer(23);

void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);

void loop()
{
// if an incoming client connects, there will be
bytes available to read:

EthernetClient client = server.available();


if (client == true) {
// read bytes from the incoming client and
write them back
// to any clients connected to the server:
server.write(client.read());
}
}

available()
Description

Gets a client that is connected to the server


and has data available for reading. The
connection persists when the returned client
object goes out of scope; you can close it by
calling client.stop().
available() inherits from the Stream utility
class.
Syntax

server.available()
Parameters

None
Returns

a Client object; if no Client has data


available for reading, this object will
evaluate to false in an if-statement (see the
example below)
Example
#include <Ethernet.h>
#include <SPI.h>
// the media access control (ethernet hardware)
address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
//the IP address for the shield:
byte ip[] = { 10, 0, 0, 177 };
// the router's gateway address:
byte gateway[] = { 10, 0, 0, 1 };
// the subnet:
byte subnet[] = { 255, 255, 0, 0 };
// telnet defaults to port 23
EthernetServer server = EthernetServer(23);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
}
void loop()
{
// if an incoming client connects, there will be
bytes available to read:
EthernetClient client = server.available();

if (client == true) {
// read bytes from the incoming client and
write them back
// to any clients connected to the server:
server.write(client.read());
}
}

write()
Description
Write data to all the clients connected
to a server. This data is sent as a byte
or series of bytes.
Syntax
server.write(val)
server.write(buf, len)
Parameters
val: a value to send as a single byte
(byte or char)
buf: an array to send as a series of
bytes (byte or char)
len: the length of the buffer
Returns
byte
write() returns the number of bytes
written. It is not necessary to read this.
Example
#include <SPI.h>
#include <Ethernet.h>
// network configuration. gateway and subnet
are optional.
// the media access control (ethernet hardware)
address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
//the IP address for the shield:
byte ip[] = { 10, 0, 0, 177 };
// the router's gateway address:
byte gateway[] = { 10, 0, 0, 1 };
// the subnet:
byte subnet[] = { 255, 255, 0, 0 };
// telnet defaults to port 23
EthernetServer server = EthernetServer(23);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
}
void loop()

{
// if an incoming client connects, there will be
bytes available to read:
EthernetClient client = server.available();
if (client == true) {
// read bytes from the incoming client and
write them back
// to any clients connected to the server:
server.write(client.read());
}
}

print()
Description
Print data to all the clients connected to
a server. Prints numbers as a
sequence of digits, each an ASCII
character (e.g. the number 123 is sent
as the three characters '1', '2', '3').
Syntax
server.print(data)
server.print(data, BASE)
Parameters
data: the data to print (char, byte, int,
long, or string)
BASE (optional): the base in which to
print numbers: BIN for binary (base 2),
DEC for decimal (base 10), OCT for
octal (base 8), HEX for hexadecimal
(base 16).
Returns
byte
print() will return the number of bytes
written, though reading that number is
optional

println()
Description
Print data, followed by a newline, to all
the clients connected to a server. Prints
numbers as a sequence of digits, each
an ASCII character (e.g. the number
123 is sent as the three characters '1',
'2', '3').
Syntax
server.println()
server.println(data)
server.println(data, BASE)
Parameters
data (optional): the data to print (char,
byte, int, long, or string)

BASE (optional): the base in which to


print numbers: BIN for binary (base 2),
DEC for decimal (base 10), OCT for
octal (base 8), HEX for hexadecimal
(base 16).
Returns
byte
println() will return the number of bytes
written, though reading that number is
optional

Client
Description
Client is the base class for all Ethernet
client based calls. It is not called
directly, but invoked whenever you use
a function that relies on it.

EthernetClient()
Description
Creates a client which can connect to a
specified internet IP address and port
(defined in
the client.connect() function).
Syntax
EthernetClient()
Parameters
None
Example
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
byte ip[] = { 10, 0, 0, 177 };
byte server[] = { 64, 233, 187, 99 }; // Google
EthernetClient client;
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /search?q=arduino
HTTP/1.0");
client.println();
} else {

Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}

HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}

Ethernet : if (EthernetClient)

Description
Indicates if the specified Ethernet client
is ready.
Syntax
if (client)
Parameters
none
Returns
boolean : returns true if the specified
client is available.
Example:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
byte ip[] = { 10, 0, 0, 177 };
byte server[] = { 64, 233, 187, 99 }; // Google
EthernetClient client;
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
while(!client){
; // wait until there is a client connected to
proceed
}
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /search?q=arduino

connected()
Description
Whether or not the client is connected.
Note that a client is considered
connected if the connection has been
closed but there is still unread data.
Syntax
client.connected()
Parameters
none
Returns
Returns true if the client is connected,
false if not.
Example
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
byte ip[] = { 10, 0, 0, 177 };
byte server[] = { 64, 233, 187, 99 }; // Google
EthernetClient client;
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
client.connect(server, 80);
delay(1000);
Serial.println("connecting...");
if (client.connected()) {

Serial.println("connected");
client.println("GET /search?q=arduino
HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}

void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);

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

if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /search?q=arduino
HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}

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

delay(1000);
Serial.println("connecting...");

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

connect()
Description
Connects to a specified IP address and
port. The return value indicates
success or failure. Also supports DNS
lookups when using a domain name.
Syntax
client.connect()
client.connect(ip, port)
client.connect(URL, port)
Parameters
ip: the IP address that the client will
connect to (array of 4 bytes)
URL: the domain name the client will
connect to (string, ex.:"arduino.cc")
port: the port that the client will connect
to (int)
Returns
Returns true if the connection
succeeds, false if not.
Example
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
byte ip[] = { 10, 0, 0, 177 };
byte server[] = { 64, 233, 187, 99 }; // Google
EthernetClient client;

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

write()
Description
Write data to the server the client is
connected to. This data is sent as a
byte or series of bytes.
Syntax
client.write(val)
client.write(buf, len)
Parameters
val: a value to send as a single byte
(byte or char)
buf: an array to send as a series of
bytes (byte or char)
len: the length of the buffer
Returns
byte
write() returns the number of bytes
written. It is not necessary to read this
value.

print()

Description
Print data to the server that a client is
connected to. Prints numbers as a
sequence of digits, each an ASCII
character (e.g. the number 123 is sent
as the three characters '1', '2', '3').
Syntax
client.print(data)
client.print(data, BASE)
Parameters
data: the data to print (char, byte, int,
long, or string)
BASE (optional): the base in which to
print numbers: DEC for decimal (base
10), OCT for octal (base 8), HEX for
hexadecimal (base 16).
Returns
byte: returns the number of bytes
written, though reading that number is
optional

println()
Description
Print data, followed by a carriage return
and newline, to the server a client is
connected to. Prints numbers as a
sequence of digits, each an ASCII
character (e.g. the number 123 is sent
as the three characters '1', '2', '3').
Syntax
client.println()
client.println(data)
client.print(data, BASE)
Parameters
data (optional): the data to print (char,
byte, int, long, or string)
BASE (optional): the base in which to
print numbers: DEC for decimal (base
10), OCT for octal (base 8), HEX for
hexadecimal (base 16).
Returns
byte: return the number of bytes
written, though reading that number is
optional

available()
Description
Returns the number of bytes available
for reading (that is, the amount of data

that has been written to the client by


the server it is connected to).
available() inherits from
the Stream utility class.
Syntax
client.available()
Parameters
none
Returns
The number of bytes available.
Example
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE,
0xED };
byte ip[] = { 10, 0, 0, 177 };
byte server[] = { 64, 233, 187, 99 }; // Google
EthernetClient client;
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /search?q=arduino
HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}

read()

Read the next byte received from the


server the client is connected to (after
the last call to read()).
read() inherits from the Stream utility
class.
Syntax
client.read()
Parameters
none
Returns
The next byte (or character), or -1 if
none is available.

#include <Ethernet.h>
#include <EthernetUdp.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 };

flush()
Discard any bytes that have been
written to the client but not yet read.
flush() inherits from the Stream utility
class.
Syntax
client.flush()
Parameters
none
Returns
none

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

stop()

EthernetUDP Udp;

Description
Disconnect from the server.
Syntax
client.stop()
Parameters
none
Returns
none
Ethernet : UDP.begin()
Description
Initializes the ethernet UDP library and
network settings.
Syntax
EthernetUDP.begin(localPort);
Parameters
localPort: the local port to listen on (int)
Returns
None
Example

unsigned int localPort = 8888;


to listen on

// An EthernetUDP instance to let us send


and receive packets over UDP

void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);

void loop() {

}
Ethernet : UDP.read()

#include <SPI.h>

// local port

Description
Reads UDP data from the specified
buffer. If no arguments are given, it will
return the next character in the buffer.
This function can only be successfully
called after UDP.parsePacket().
Syntax
UDP.read();
UDP.read(packetBuffer, MaxSize);
Parameters
packetBuffer: buffer to hold incoming
packets (char)
MaxSize: maximum size of the buffer
(int)
Returns
char : returns the characters in the
buffer
Example
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.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, 177);
unsigned int localPort = 8888;
listen on

// local port to

// An EthernetUDP instance to let us send and


receive packets over UDP
EthernetUDP Udp;
char packetBuffer[UDP_TX_PACKET_MAX_SIZ
E]; //buffer to hold incoming packet,
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);

{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer,UDP_TX_PACKET_M
AX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
}
}

Ethernet : UDP.write()

Description
Writes UDP data to the remote
connection. Must be wrapped
between beginPacket() and endPacket().
beginPacket() initializes the packet of
data, it is not sent until endPacket() is
called.
Syntax
UDP.write(message);
UDP.write(buffer, size);
Parameters
message: the outgoing message (char)
buffer: an array to send as a series of
bytes (byte or char)
size: the length of the buffer
Returns
byte : returns the number of characters
sent. This does not have to be read
Example

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

}
void loop() {
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)

// 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, 177);

unsigned int localPort = 8888;


to listen on

Returns
None
Example
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// local port

// An EthernetUDP instance to let us send


and receive packets over UDP

// 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, 177);

EthernetUDP Udp;

unsigned int localPort = 8888;


listen on

void setup() {

// An EthernetUDP instance to let us send and


receive packets over UDP
EthernetUDP Udp;

// start the Ethernet and UDP:


Ethernet.begin(mac,ip);
Udp.begin(localPort);
}

// local port to

void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
}
void loop() {

void loop() {
Udp.beginPacket(Udp.remoteIP(),
Udp.remotePort());
Udp.write("hello");
Udp.endPacket();
}
Ethernet : UDP.beginPacket()

Description
Starts a connection to write UDP data
to the remote connection
Syntax
UDP.beginPacket(remoteIP,
remotePort);
Parameters
remoteIP: the IP address of the remote
connection (4 bytes)
remotePort: the port of the remote
connection (int)

Udp.beginPacket(Udp.remoteIP(), Udp.remote
Port());
Udp.write("hello");
Udp.endPacket();
}

Ethernet : UDP.endPacket()

Description
Called after writing UDP data to the
remote connection.
Syntax
UDP.endPacket();
Parameters
None
Returns
None
Example
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.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, 177);

receive packets over UDP


EthernetUDP Udp;

unsigned int localPort = 8888;


listen on

void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);

// local port to

// An EthernetUDP instance to let us send and


receive packets over UDP
EthernetUDP Udp;

Serial.begin(9600);
}

void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
}
void loop() {
Udp.beginPacket(Udp.remoteIP(), Udp.remote
Port());
Udp.write("hello");
Udp.endPacket();

Ethernet : UDP.available()

available()

Ethernet : UDP.parsePacket()

Description
Checks for the presence of a UDP
packet, and reports the size.
parsePacket() must be called before
reading the buffer with UDP.read().
Syntax
UDP.parsePacket();
Parameters
None
Returns
int: the size of a received UDP packet
Example
#include <SPI.h>
// needed for Arduino
versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h>
// UDP library
from: bjoern@cs.stanford.edu 12/30/2008
// 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, 177);
unsigned int localPort = 8888;
listen on

void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
}
delay(10);
}

// local port to

// An EthernetUDP instance to let us send and

Description
Get the number of bytes (characters)
available for reading from the buffer.
This is data that's already arrived.
This function can only be successfully
called after UDP.parsePacket().
available() inherits from
the Stream utility class.
Syntax
UDP.available()
Parameters
None
Returns
the number of bytes available to read
Example
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.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, 177);
unsigned int localPort = 8888;
listen on

// local port to

// An EthernetUDP instance to let us send and


receive packets over UDP
EthernetUDP Udp;

char packetBuffer[UDP_TX_PACKET_MAX_SIZ
E]; //buffer to hold incoming packet,
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
}
void loop() {
int packetSize = Udp.parsePacket();
if(Udp.available())
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer,UDP_TX_PACKET_M
AX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
}
}

Syntax
UDP.remoteIP();
Parameters
None
Returns
4 bytes : the IP address of the remote
connection
Example
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.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, 177);
unsigned int localPort = 8888;
listen on

// An EthernetUDP instance to let us send and


receive packets over UDP
EthernetUDP Udp;
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
}
void loop() {
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From IP : ");

stop()
Description
Disconnect from the server. Release
any resource being used during the
UDP session.
Syntax
EthernetUDP.stop()
Parameters
none
Returns
none
Ethernet : UDP.remoteIP()

Description
Gets the IP address of the remote
connection.
This function must be called
after UDP.parsePacket().

// local port to

IPAddress remote = Udp.remoteIP();


//print out the remote connection's IP address
Serial.print(remote);
Serial.print(" on port : ");
//print out the remote connection's port
Serial.println(Udp.remotePort());
}
}

Ethernet : UDP.remotePort()

Description
Gets the port of the remote UDP
connection.

// read the packet into packetBufffer


Udp.read(packetBuffer,UDP_TX_PACKET_M
AX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
}
}

This function must be called


after UDP.parsePacket().
Syntax
UDP.remotePort();
Parameters
None
Returns
int : the port of the UDP connection to a
remote host
Example
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.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, 177);
unsigned int localPort = 8888;
listen on

// local port to

// An EthernetUDP instance to let us send and


receive packets over UDP
EthernetUDP Udp;
char packetBuffer[UDP_TX_PACKET_MAX_SIZ
E]; //buffer to hold incoming packet,
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
}
void loop() {
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());

Chat Server
A simple server that distributes any
incoming messages to all connected
clients. To use, open a terminal
window, telnet to your devices IP
address, and type away. Any incoming
text will be sent to all connected clients
(including the one typing). Additionally,
you will be able to see the client's input
in your serial monitor as well.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the Ethernet shield.
Schematic

Code:
/*
Chat Server
A simple server that distributes any
incoming messages to all
connected clients. To use telnet to your

device's IP address and type.


You can see the client's input in the serial
monitor as well.
Using an Arduino Wiznet Ethernet shield.

void loop() {
// wait for a new client:
EthernetClient client = server.available();

Circuit:
* Ethernet shield attached to pins 10, 11,
12, 13
* Analog inputs attached to pins A0 through
A5 (optional)

// when the client sends the first byte, say


hello:
if (client) {
if (!alreadyConnected) {
// clead out the input buffer:
client.flush();
Serial.println("We have a new client");
client.println("Hello, client!");
alreadyConnected = true;
}

created 18 Dec 2009


by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
*/

if (client.available() > 0) {
// read the bytes incoming from the
client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
}

#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.
// gateway and subnet are optional:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 177);
IPAddress gateway(192,168,1, 1);
IPAddress subnet(255, 255, 0, 0);
// telnet defaults to port 23
EthernetServer server(23);
boolean alreadyConnected = false; //
whether or not the client was connected
previously
void setup() {
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
// Open serial communications and wait for
port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed
for Leonardo only
}
Serial.print("Chat server address:");
Serial.println(Ethernet.localIP());
}

Web Client
This example shows you how to make
a HTTP request using an Ethernet
shield. It returns a Google search for
the term "Arduino". The results of this
search are viewable as HTML through
your Arduino's serial window.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the Ethernet shield.
Schematic

Code:
/*
Web client
This sketch connects to a website
(http://www.google.com)
using an Arduino Wiznet Ethernet shield.

Circuit:
* Ethernet shield attached to pins 10, 11,
12, 13
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe, based on work by Adrian
McEwen
*/
#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 shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x
FE, 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,0,177);
// 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 Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet
using DHCP");
// no point in carrying on, so do nothing
forevermore:

// try to congifure using IP address


instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to
initialize:
delay(1000);
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 {
// kf 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);
}
}

Web Client Repeating


This example shows you how to make
repeated HTTP requests using an
Ethernet shield. This example uses
DNS, by assigning the Ethernet client
with a MAC address, IP address, and
DNS address. It connects

tohttp://www.arduino.cc/latest.txt. The
conent of the page is viewable through
your Arduino's serial window.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the Ethernet shield.
Schematic

Code:
/*
Repeating Web client
This sketch connects to a a web server and
makes a request
using a Wiznet Ethernet shield. You can

use the Arduino Ethernet shield, or


the Adafruit Ethernet shield, either one will
work, as long as it's got
a Wiznet Ethernet module on board.
This example uses DNS, by assigning the
Ethernet client with a MAC address,
IP address, and DNS address.
Circuit:
* Ethernet shield attached to pins 10, 11,
12, 13
created 19 Apr 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/WebClientRepe
ating
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
// assign a MAC address for the ethernet
controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your
network here,
// for manual configuration:
IPAddress ip(10,0,0,20);
// fill in your Domain Name Server address
here:
IPAddress myDns(1,1,1,1);
// initialize the library instance:
EthernetClient client;
char server[] = "www.arduino.cc";
unsigned long lastConnectionTime = 0;
// last time you connected to the server, in
milliseconds
boolean lastConnected = false;
//
state of the connection last time through the
main loop
const unsigned long postingInterval = 60*10
00; // delay between updates, in
milliseconds
void setup() {
// start serial port:

Serial.begin(9600);
// give the ethernet module time to boot up:
delay(1000);
// start the Ethernet connection using a
fixed IP address and DNS server:
Ethernet.begin(mac, ip, myDns);
// print the Ethernet board/shield's IP
address:
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
}
void loop() {
// if there's incoming data from the net
connection.
// send it out the serial port. This is for
debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there
was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds
have passed since
// your last connection, then connect again
and send data:
if(!client.connected() && (millis() lastConnectionTime > postingInterval)) {
httpRequest();
}
// store the state of the connection for next
time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to
the server:
void httpRequest() {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.println("GET /latest.txt HTTP/1.1");
client.println("Host: www.arduino.cc");
client.println("User-Agent: arduino-

ethernet");
client.println("Connection: close");
client.println();
// note the time that the connection was
made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println("disconnecting.");
client.stop();
}
}

Web Server
In this example, you will use your
Ethernet Shield and your Arduino to
create a simple Web server. Using the
Ethernet library, your device will be
able to answer a HTTP request with
your Ethernet shield. After opening a
browser and navigating to your
Ethernet shield's IP address, your
Arduino will respond with just enough
HTML for a browser to display the input
values from all six analog pins.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield.
Schematic

Circuit:
* Ethernet shield attached to pins 10, 11,
12, 13
* Analog inputs attached to pins A0 through
A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
*/
#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,177);
// 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 Leonardo only
}
// start the Ethernet connection and the
server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}

Code
/*
Web Server
A simple web server that shows the value
of the analog input pins.
using an Arduino Wiznet Ethernet shield.

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 closed after
completion of the response
client.println("Refresh: 5"); // refresh the
page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog
input pin
for (int analogChannel = 0; analogCha
nnel < 6; analogChannel++) {
int sensorReading = analogRead(an
alogChannel);
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");

}
}

Xively Client
This example shows you how to
answer a HTTP request using an
Ethernet shield. Specifically, it connects
to xively.com, a free datalogging site.
The example requires that you set up a
pachube.com account, as well as a
pachube feed (for more information on
setting up an input feed, please click
here). Your Ethernet shield will then
connect to that feed and upload sensor
data every 10 seconds.
Hardware Required
Arduino Ethernet Shield or Arduino
Ethernet
Shield-compatible Arduino board
One analog sensor to attached to the
Ethernet Shield
Software Required
xively.com account
pachube.com feed that accepts two
data items
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield. You could also use an Arduino
Ethernet board.
Schematic

Pictured: One CDS photocell with 10k


ohm pull down resistor on analog pin 0.
Code
/*
Xively sensor client
This sketch connects an analog sensor to
Xively (http://www.xively.com)
using a Wiznet Ethernet shield. You can
use the Arduino Ethernet shield, or
the Adafruit Ethernet shield, either one will
work, as long as it's got
a Wiznet Ethernet module on board.

This example has been updated to use


version 2.0 of the Xively.com API.
To make it work, create a feed with a
datastream, and give it the ID
sensor1. Or change the code below to
match your feed.
Circuit:
* Analog sensor attached to analog in 0
* Ethernet shield attached to pins 10, 11,
12, 13
created 15 March 2010
modified 9 Apr 2012
by Tom Igoe with input from Usman Haque
and Joe Saavedra
http://arduino.cc/en/Tutorial/XivelyClient
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
#define APIKEY
"YOUR API KEY
GOES HERE" // replace your xively api key
here
#define FEEDID
00000 // replace your
feed ID
#define USERAGENT
"My Project" //
user agent is the project name
// assign a MAC address for the ethernet
controller.
// Newer Ethernet shields have a MAC
address printed on a sticker on the shield
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your
network here,
// for manual configuration:
IPAddress ip(10,0,1,20);
// initialize the library instance:
EthernetClient client;
// 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(216,52,233,122);
//
numeric IP for api.xively.com
//char server[] = "api.xively.com"; // name

address for xively API


unsigned long lastConnectionTime = 0;
// last time you connected to the server, in
milliseconds
boolean lastConnected = false;
//
state of the connection last time through the
main loop
const unsigned long postingInterval = 10*10
00; //delay between updates to Xively.com
void setup() {
// Open serial communications and wait for
port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed
for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet
using DHCP");
// DHCP failed, so use a fixed IP address:
Ethernet.begin(mac, ip);
}
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// if there's incoming data from the net
connection.
// send it out the serial port. This is for
debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there
was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds
have passed since
// your last connection, then connect again

and send data:


if(!client.connected() && (millis() lastConnectionTime > postingInterval)) {
sendData(sensorReading);
}
// store the state of the connection for next
time through
// the loop:
lastConnected = client.connected();
}

// this method makes a HTTP connection to


the server:
void sendData(int thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-XivelyApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");

int getLength(int someValue) {


// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}

// This method calculates the number of


digits in the
// sensor reading. Since each digit of the
ASCII decimal
// representation is a byte, the number of
digits equals
// the number of bytes:

// calculate the length of the sensor


reading in bytes:
// 8 bytes for "sensor1," + number of digits
of the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT
request:
client.print("sensor1,");
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was
made or attempted:
lastConnectionTime = millis();

Xively Client using Strings


This example shows you how to
answer a HTTP request using an
Ethernet shield. Specifically, it connects
to xively.com, a free datalogging site.
The example requires that you set up a
xively.com account, as well as a
pachube feed (for more information on
setting up an input feed, please click
here). Your Ethernet shield will then
connect to that feed and upload sensor
data every 10 seconds.
Additionally, this example shows how
to send sensor data as a string.
Hardware Required
Arduino Ethernet Shield or Arduino
Ethernet board
Shield-compatible Arduino board
Two analog sensors to attached to the
Ethernet Shield
Software Required
xively.com account
xively.com feed that accepts one data
item
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to

the Arduino via the SPI bus. It uses


pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

Pictured: One CDS photocells with a


10k ohm pull down resistor on analog
pin 0.
Code
image developed using Fritzing. For more
circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield. Or you could use an Arduino
Ethernet board.
Schematic

/*
Xively sensor client with Strings
This sketch connects an analog sensor to
Xively (http://www.xively.com)
using a Wiznet Ethernet shield. You can
use the Arduino Ethernet shield, or
the Adafruit Ethernet shield, either one will
work, as long as it's got
a Wiznet Ethernet module on board.

This example has been updated to use


version 2.0 of the xively.com API.
To make it work, create a feed with two
datastreams, and give them the IDs
sensor1 and sensor2. Or change the code
below to match your feed.
This example uses the String library, which
is part of the Arduino core from
version 0019.
Circuit:
* Analog sensor attached to analog in 0
* Ethernet shield attached to pins 10, 11,
12, 13
created 15 March 2010
modified 9 Apr 2012
by Tom Igoe with input from Usman Haque
and Joe Saavedra
modified 8 September 2012
by Scott Fitzgerald
http://arduino.cc/en/Tutorial/XivelyClientStri
ng
This code is in the public domain.

// 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(216,52,233,121);
//
numeric IP for api.xively.com
//char server[] = "api.xively.com"; // name
address for xively API
unsigned long lastConnectionTime = 0;
// last time you connected to the server, in
milliseconds
boolean lastConnected = false;
//
state of the connection last time through the
main loop
const unsigned long postingInterval = 10*10
00; //delay between updates to xively.com
void setup() {
// Open serial communications and wait for
port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed
for Leonardo only
}

*/
#include <SPI.h>
#include <Ethernet.h>
#define APIKEY
"YOUR API KEY
GOES HERE" // replace your Xively api key
here
#define FEEDID
00000 // replace your
feed ID
#define USERAGENT
"My Project" //
user agent is the project name
// assign a MAC address for the ethernet
controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your
network here,
// for manual configuration:
IPAddress ip(10,0,1,20);
// initialize the library instance:
EthernetClient client;

// give the ethernet module time to boot up:


delay(1000);
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet
using DHCP");
// DHCP failed, so use a fixed IP address:
Ethernet.begin(mac, ip);
}
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// convert the data to a String to send it:
String dataString = "sensor1,";
dataString += sensorReading;
// you can append multiple readings to this
String if your
// xively feed is set up to handle multiple
values:
int otherSensorReading = analogRead(A1);
dataString += "\nsensor2,";
dataString += otherSensorReading;

// if there's incoming data from the net


connection.
// send it out the serial port. This is for
debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}

// here's the actual content of the PUT


request:
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was
made or attempted:
lastConnectionTime = millis();
}

// if there's no net connection, but there


was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds
have passed since
// your last connection, then connect again
and send data:
if(!client.connected() && (millis() lastConnectionTime > postingInterval)) {
sendData(dataString);
}
// store the state of the connection for next
time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to
the server:
void sendData(String thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-xivelyApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(thisData.length());
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();

Barometric Pressure Web Server


This example shows how to use SPI
communications to read data from a
SCP1000 Barometric Pressure sensor,
and how to then post that data to the
web by using your Arduino/Ethernet
Shield combo as a simple web server.
Using the Ethernet library, your device
will be able to answer HTTP requests
by responding with just enough HTML
for a browser to display the
temperature and barometric pressure
values outputted by your sensor. After
completing your circuit and uploading
the example code below, simply
navigate to your Ethernet shield's IP
address, in a browser, to see this
information.
See the Barometric Pressure
Sensor example for more on how the
sensor works.
Hardware Required
SCP1000 Pressure Sensor Breakout
Board
Arduino Ethernet Shield
Circuit
Your Barometric Pressure sensor will
be attached to pins 6,7, and 11 - 13 of
your Arduino/Ethernet shield combo,
and powered via your device's 3.3 volt
output. Connect the DRDY (Data
Ready) pin on your sensor to digital pin
6 on your combo, and the CSB pin
(Chip Select) to digital pin 7. Your
sensor's MOSI (Master Out Slave In)
pin should then be connected to digital

pin 11, and it's counterpart MISO


(Master In Slave Out) to digital pin 12.
Finally, connect the SCK pin, the SPI
clock input on your sensor, to digital pin
13 on your device, and make sure that
the two share a common ground.
After wiring your sensor, your shield
should be connected to a network with
an ethernet cable. You will need to
change the network settings in the
program to correspond to your network.

Code
image developed using Fritzing. For more
circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the Ethernet shield.
Schematic

/*
SCP1000 Barometric Pressure Sensor
Display
Serves the output of a Barometric Pressure
Sensor as a web page.
Uses the SPI library. For details on the
sensor, see:
http://www.sparkfun.com/commerce/produc
t_info.php?products_id=8161
http://www.vti.fi/en/support/obsolete_produc
ts/pressure_sensors/
This sketch adapted from Nathan Seidle's
SCP1000 example for PIC:
http://www.sparkfun.com/datasheets/Senso

rs/SCP1000-Testing.zip

long lastReadingTime = 0;

Circuit:
SCP1000 sensor attached to pins 6,7, and
11 - 13:
DRDY: pin 6
CSB: pin 7
MOSI: pin 11
MISO: pin 12
SCK: pin 13

void setup() {
// start the SPI library:
SPI.begin();

created 31 July 2010


by Tom Igoe
*/

// initalize the data ready and chip select


pins:
pinMode(dataReadyPin, INPUT);
pinMode(chipSelectPin, OUTPUT);

#include <Ethernet.h>
// the sensor communicates using SPI, so
include the library:
#include <SPI.h>
// assign a MAC address for the ethernet
controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// assign an IP address for the controller:
IPAddress ip(192,168,1,20);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255, 255, 255, 0);
// Initialize the Ethernet server library
// with the IP address and port you want to
use
// (port 80 is default for HTTP):
EthernetServer server(80);
//Sensor's memory register addresses:
const int PRESSURE = 0x1F;
//3 most
significant bits of pressure
const int PRESSURE_LSB = 0x20; //16
least significant bits of pressure
const int TEMPERATURE = 0x21; //16 bit
temperature reading
// pins used for the connection with the
sensor
// the others you need are controlled by the
SPI library):
const int dataReadyPin = 6;
const int chipSelectPin = 7;
float temperature = 0.0;
long pressure = 0;

// start the Ethernet connection and the


server:
Ethernet.begin(mac, ip);
server.begin();

Serial.begin(9600);
//Configure SCP1000 for low noise
configuration:
writeRegister(0x02, 0x2D);
writeRegister(0x01, 0x03);
writeRegister(0x03, 0x02);
// give the sensor and Ethernet shield time
to set up:
delay(1000);
//Set the sensor to high resolution mode tp
start readings:
writeRegister(0x03, 0x0A);
}
void loop() {
// check for a reading no more than once a
second.
if (millis() - lastReadingTime > 1000){
// if there's a reading ready, read it:
// don't do anything until the data ready
pin is high:
if (digitalRead(dataReadyPin) == HIGH) {
getData();
// timestamp the last time you got a
reading:
lastReadingTime = millis();
}
}
// listen for incoming Ethernet connections:
listenForEthernetClients();
}
void getData() {
Serial.println("Getting reading");

//Read the temperature data


int tempData = readRegister(0x21, 2);
// convert the temperature to celsius and
display it:
temperature = (float)tempData / 20.0;
//Read the pressure data highest 3 bits:
byte pressureDataHigh = readRegister(0x
1F, 1);
pressureDataHigh &= 0b00000111; //you
only needs bits 2 to 0
//Read the pressure data lower 16 bits:
unsigned int pressureDataLow = readRegis
ter(0x20, 2);
//combine the two parts into one 19-bit
number:
pressure = ((pressureDataHigh << 16) | pre
ssureDataLow)/4;
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" degrees C");
Serial.print("Pressure:
" + String(pressure));
Serial.println(" Pa");
}
void listenForEthernetClients() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("Got a client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// 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();
// print the current readings, in HTML
format:
client.print("Temperature: ");
client.print(temperature);
client.print(" degrees C");

client.println("<br />");
client.print("Pressure:
" + String(pressure));
client.print(" Pa");
client.println("<br />");
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();
}
}
//Send a write command to SCP1000
void writeRegister(byte registerName, byte r
egisterValue) {
// SCP1000 expects the register name in
the upper 6 bits
// of the byte:
registerName <<= 2;
// command (read or write) goes in the
lower two bits:
registerName |= 0b00000010; //Write
command
// take the chip select low to select the
device:
digitalWrite(chipSelectPin, LOW);
SPI.transfer(registerName); //Send register
location
SPI.transfer(registerValue); //Send value to
record into register
// take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH);
}
//Read register from the SCP1000:
unsigned int readRegister(byte registerNam
e, int numBytes) {

byte inByte = 0;
// incoming from the
SPI read
unsigned int result = 0; // result to return
// SCP1000 expects the register name in
the upper 6 bits
// of the byte:
registerName <<= 2;
// command (read or write) goes in the
lower two bits:
registerName &= 0b11111100; //Read
command
// take the chip select low to select the
device:
digitalWrite(chipSelectPin, LOW);
// send the device the register you want to
read:
int command = SPI.transfer(registerName);

The Ethernet shield allows you to


connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

// send a value of 0 to read the first byte


returned:
inByte = SPI.transfer(0x00);
result = inByte;
// if there's more than one byte returned,
// shift the first byte then get the second
byte:
if (numBytes > 1){
result = inByte << 8;
inByte = SPI.transfer(0x00);
result = result |inByte;
}
// take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH);
// return the result:
return(result);
}

Sending and Receiving String via UDP


In this example, you will use your
Ethernet Shield and your Arduino to
send and receive text strings via the
UDP protocol (Universal Datagram
Packet). You'll need another device to
send to and from.
The Processing sketch included at the
end of the code will send to and receive
from your Arduino running this
example.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Circuit

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield.
Schematic

A Processing sketch is included at the end


of file that can be used to send
and received messages for testing with a
computer.
created 21 Aug 2010
by Michael Margolis
This code is in the public domain.
*/
#include <SPI.h>
// needed for Arduino
versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h>
// UDP
library from: bjoern@cs.stanford.edu
12/30/2008
// 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, 177);
unsigned int localPort = 8888;
to listen on

// local port

// buffers for receiving and sending data


char packetBuffer[UDP_TX_PACKET_MAX
_SIZE]; //buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged";
//
a string to send back
// An EthernetUDP instance to let us send
and receive packets over UDP
EthernetUDP Udp;
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
Serial.begin(9600);

Code
/*
UDPSendReceive.pde:
This sketch receives UDP message strings,
prints them to the serial port
and sends an "acknowledge" string back to
the sender

}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");

Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());

void draw()
{
}
void keyPressed() {
String ip
= "192.168.1.177"; // the
remote IP address
int port
= 8888;
// the destination
port
udp.send("Hello World", ip, port ); // the
message to send
}

// read the packet into packetBufffer


Udp.read(packetBuffer,UDP_TX_PACKE
T_MAX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);

void receive( byte[] data ) {


// <-default handler
//void receive( byte[] data, String ip, int port
) { // <-- extended handler

// send a reply, to the IP address and port


that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.re
motePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
delay(10);
}

for(int i=0; i < data.length; i++)


print(char(data[i]));
println();
}
*/
[Get Code]

Processing Code
Copy the Processing sketch from the
code sample above. When you type
any letter in the Processing sketch
window, it will send a string to the
Arduino via UDP.

/*
Processing sketch to run with this example
=================================
====================
// Processing UDP example to send and
receive string data from Arduino
// press any key to send the "Hello Arduino"
message
import hypermedia.net.*;

UDP udp; // define the UDP object


void setup() {
udp = new UDP( this, 6000 ); // create a
new datagram connection on port 6000
//udp.log( true );
// <-- printout the
connection activity
udp.listen( true );
// and wait for
incoming message
}

Network Time Protocol (NTP) Client


In this example, you will use your
Ethernet Shield and your Arduino to
query a Network Time Protocol (NTP)
server. This way, your Arduino can get
the time from the Internet.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.

The shield should be connected to a


network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield.
Schematic

Code
/*
Udp NTP Client
Get the time from a Network Time Protocol
(NTP) time server

Demonstrates use of UDP sendPacket and


ReceivePacket
For more on NTP time servers and the
messages needed to communicate with
them,
see
http://en.wikipedia.org/wiki/Network_Time_P
rotocol
Warning: NTP Servers are subject to
temporary failure or IP address change.
Plese check

packets over UDP


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

http://tf.nist.gov/tf-cgi/servers.cgi
if the time server used in the example didn't
work.
created 4 Sep 2010
by Michael Margolis
modified 9 Apr 2012
by Tom Igoe
This code is in the public domain.

// start Ethernet and UDP


if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet
using DHCP");
// no point in carrying on, so do nothing
forevermore:
for(;;)
;
}
Udp.begin(localPort);
}

*/
void loop()
{
sendNTPpacket(timeServer); // send an
NTP packet to a time server

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// Enter a MAC address for your controller
below.
// Newer Ethernet shields have a MAC
address printed on a sticker on the shield
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
unsigned int localPort = 8888;
to listen for UDP packets

// wait to see if a reply is available


delay(1000);
if ( Udp.parsePacket() ) {
// We've received a packet, read the data
from it
Udp.read(packetBuffer,NTP_PACKET_SI
ZE); // read the packet into the buffer

// local port

IPAddress timeServer(132, 163, 4, 101); //


time-a.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 102); //
time-b.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 103); //
time-c.timefreq.bldrdoc.gov NTP server
const int NTP_PACKET_SIZE= 48; // NTP
time stamp is in the first 48 bytes of the
message
byte packetBuffer[ NTP_PACKET_SIZE]; //b
uffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive

//the timestamp starts at byte 40 of the


received packet and is four bytes,
// or two words, long. First, esxtract the
two words:
unsigned long highWord = word(packetBu
ffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuf
fer[42], packetBuffer[43]);
// combine the four bytes (two words) into
a long integer
// this is NTP time (seconds since Jan 1
1900):
unsigned long secsSince1900 = highWor
d << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 =
" );

Serial.println(secsSince1900);

packetBuffer[0] = 0b11100011; // LI,


Version, Mode
packetBuffer[1] = 0; // Stratum, or type of
clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock
Precision
// 8 bytes of zero for Root Delay & Root
Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;

// now convert NTP time into everyday


time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In
seconds, that's 2208988800:
const unsigned long seventyYears = 2208
988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 seventyYears;
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print("The UTC time is ");
//
UTC is the time at Greenwich Meridian
(GMT)
Serial.print((epoch % 86400L) / 3600); //
print the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
// In the first 10 minutes of each hour,
we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print
the minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 ) {
// In the first 10 seconds of each minute,
we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch %60); // print the
second
}
// wait ten seconds before asking for the
time again
delay(10000);
}
// send an NTP request to the time server at
the given address
unsigned long sendNTPpacket(IPAddress&
address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_S
IZE);
// Initialize values needed to form NTP
request
// (see URL above for details on the
packets)

// all NTP fields have been given values,


now
// you can send a packet requesting a
timestamp:
Udp.beginPacket(address, 123); //NTP
requests are to port 123
Udp.write(packetBuffer,NTP_PACKET_SIZ
E);
Udp.endPacket();
}

DNS Web Client


This example connects to a named
server using an Ethernet shield. The
sketch illustrates how to connect using
DHCP and DNS. When calling
Ethernet.begin(mac), the Etehrnet
library attempts to obtain an IP address
using DHCP. Using DHCP significantly
adds to the sketch size; be sure there
is enough space to run the program.
DNS lookup happens when
client.connect(servername,port) is
called. servername is a URL string, like
"www.arduino.cc".
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.

The shield should be connected to a


network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0x


DE, 0x02 };
char serverName[] = "www.google.com";
// 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 Leonardo only
}

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield.
Code
/*
DNS and DHCP-based Web client
This sketch connects to a website
(http://www.google.com)
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11,
12, 13
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe, based on work by Adrian
McEwen
*/
#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 shield

// start the Ethernet connection:


if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet
using DHCP");
// no point in carrying on, so do nothing
forevermore:
while(true);
}
// give the Ethernet shield a second to
initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via
serial:
if (client.connect(serverName, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /search?q=arduino
HTTP/1.0");
client.println();
}
else {
// kf 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);
}

the program to correspond to your


network.

// if the server's disconnected, stop the


client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while(true);
}
}

DHCP Chat Server


This example connects to a Telnet
server using an Ethernet shield.
Messages from the server are printed
out via the serial port. Messages can
be sent to the remote server serially as
well. The Serial monitor works well for
this purpose.
This version attempts to get an IP
address using DHCP. An IP address
can be assigned via DHCP when
Ethernet.begin(mac) is called. Be
careful, when using the DHCP
extensions, sketch size increases
significantly.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Software Required
A telnet server
Alternatively, Processing has
a ChatServer example that works well
for this purpose
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield.
Code
/*
DHCP Chat Server
A simple server that distributes any
incoming messages to all
connected clients. To use telnet to your
device's IP address and type.
You can see the client's input in the serial
monitor as well.
Using an Arduino Wiznet Ethernet shield.
THis version attempts to get an IP address
using DHCP
Circuit:
* Ethernet shield attached to pins 10, 11,
12, 13
created 21 May 2011
modified 9 Apr 2012
by Tom Igoe
Based on ChatServer example by David A.
Mellis
*/
#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.
// gateway and subnet are optional:
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
IPAddress ip(192,168,1, 177);
IPAddress gateway(192,168,1, 1);
IPAddress subnet(255, 255, 0, 0);

// when the client sends the first byte, say


hello:
if (client) {
if (!gotAMessage) {
Serial.println("We have a new client");
client.println("Hello, client!");
gotAMessage = true;
}

// telnet defaults to port 23


EthernetServer server(23);
boolean gotAMessage = false; // whether or
not you got a message from the client yet

// read the bytes incoming from the client:


char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.print(thisChar);

void setup() {
// Open serial communications and wait for
port to open:
Serial.begin(9600);
// this check is only needed on the
Leonardo:
while (!Serial) {
; // wait for serial port to connect. Needed
for Leonardo only
}
// start the Ethernet connection:
Serial.println("Trying to get an IP address
using DHCP");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet
using DHCP");
// initialize the ethernet device not using
DHCP:
Ethernet.begin(mac, ip, gateway, subnet);
}
// print your local IP address:
Serial.print("My IP address: ");
ip = Ethernet.localIP();
for (byte thisByte = 0; thisByte < 4; thisByte
++) {
// print the value of each byte of the IP
address:
Serial.print(ip[thisByte], DEC);
Serial.print(".");
}
Serial.println();
// start listening for clients
server.begin();
}
void loop() {
// wait for a new client:
EthernetClient client = server.available();

}
}

DHCP Address Printer


This sketch uses the DHCP extensions
to the Ethernet library to get an IP
address via DHCP and print the
address obtained using an Arduino
Ethernet shield.
DHCP is used to assign an IP address
when Ethernet.begin(mac) is called.
Using DHCP significantly increases the
size of a sketch. Using the localIP()
function, the assigned IP address is
sent out via the serial monitor.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

default for HTTP):


EthernetClient client;
void setup() {
// Open serial communications and wait for
port to open:
Serial.begin(9600);
// this check is only needed on the
Leonardo:
while (!Serial) {
; // wait for serial port to connect. Needed
for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet
using DHCP");
// no point in carrying on, so do nothing
forevermore:
for(;;)
;
}
// print your local IP address:
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte
++) {
// print the value of each byte of the IP
address:
Serial.print(Ethernet.localIP()[thisByte], D
EC);
Serial.print(".");
}
Serial.println();
}

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield.
Code
/*
DHCP-based IP printer
This sketch uses the DHCP extensions to
the Ethernet library
to get an IP address via DHCP and print the
address obtained.
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11,
12, 13

void loop() {

created 12 April 2011


modified 9 Apr 2012
by Tom Igoe

*/
#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 shield
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is

Telnet Client
This example connects to a Telnet
server using an Ethernet shield.
Messages from the server are printed
out via the serial port. Messages can
be sent to the remote server serially as
well. The Serial monitor works well for
this purpose.
Hardware Required
Arduino Ethernet Shield
Shield-compatible Arduino board
Software Required
A telnet server

Alternatively, Processing has


a ChatServer example that works well
for this purpose
Circuit
The Ethernet shield allows you to
connect a WizNet Ethernet controller to
the Arduino via the SPI bus. It uses
pins 10, 11, 12, and 13 for the SPI
connection to the WizNet. Later models
of the Ethernet shield also have an SD
Card on board. Digital pin 4 is used to
control the slave select pin on the SD
card.
The shield should be connected to a
network with an ethernet cable. You will
need to change the network settings in
the program to correspond to your
network.

in the Processing application, available at


http://processing.org/
Circuit:
* Ethernet shield attached to pins 10, 11,
12, 13
created 14 Sep 2010
modified 9 Apr 2012
by Tom Igoe
*/
#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,177);
// Enter the IP address of the server you're
connecting to:
IPAddress server(1,1,1,1);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 23 is
default for telnet;
// if you're using Processing's ChatServer,
use port 10002):
EthernetClient client;

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, your Arduino


would be stacked below the Ethernet
shield.
Code
/*
Telnet client
This sketch connects to a a telnet server
(http://www.google.com)
using an Arduino Wiznet Ethernet
shield. You'll need a telnet server
to test this with.
Processing's ChatServer example (part of
the network library) works well,
running on port 10002. It can be found as
part of the examples

void setup() {
// start the Ethernet connection:
Ethernet.begin(mac, ip);
// Open serial communications and wait for
port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed
for Leonardo only
}
// give the Ethernet shield a second to
initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via
serial:
if (client.connect(server, 10002)) {

Serial.println("connected");
}
else {
// if you didn't get a connection to the
server:
Serial.println("connection failed");
}
}

begin(long)

start the library and override the default


baud rate
printVersion()

send the protocol version to the host


computer
blinkVersion()

blink the protocol version on pin 13


printFirmwareVersion()

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);
}
// as long as there are bytes in the serial
queue,
// read them and send them out the socket
if it's open:
while (Serial.available() > 0) {
char inChar = Serial.read();
if (client.connected()) {
client.print(inChar);
}
}
// if the server's disconnected, stop the
client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing:
while(true);
}
}

Firmata Library
The Firmata library implements the
Firmata protocol for communicating
with software on the host computer.
This allows you to write custom
firmware without having to create your
own protocol and objects for the
programming environment that you are
using.

Methods
begin()

start the library

send the firmware name and version to


the host computer
setFirmwareVersion(byte major, byte minor)

set the firmware name and version,


using the sketch's filename, minus
the .pde
Sending Messages
sendAnalog(byte pin, int value)

send an analog message


sendDigitalPorts(byte pin, byte firstPort, byte
secondPort)

send digital ports as individual bytes


sendDigitalPortPair(byte pin, int value)

send digital ports as one int


sendSysex(byte command, byte bytec, byte* bytev)

send a command with an arbitrary


array of bytes
sendString(const char* string)

send a string to the host computer


sendString(byte command, const char* string)

send a string to the host computer


using a custom command type
Receiving Messages
available()

check to see if there are any incoming


messages in the buffer
processInput()

process incoming messages from the


buffer, sending the data to any
registered callback functions
attach(byte command, callbackFunction myFunction)

attach a function to an incoming


message type
detach(byte command)

detach a function from an incoming


message type

Callback Functions
In order to attach your function to a
message type, your function must
match the standard callback function.
There are currently three types of
callback functions in
Firmata: generic, string, and sysex.
generic
void callbackFunction(byte pin, int value);

void loop()
{
while(Firmata.available()) {
Firmata.processInput();
}
for(analogPin = 0; analogPin <
TOTAL_ANALOG_PINS; analogPin++) {
Firmata.sendAnalog(analogPin,
analogRead(analogPin));
}
}

system_reset
void systemResetCallbackFunction(void);

string
void stringCallbackFunction(char *myString);

sysex
void sysexCallbackFunction(byte pin, byte byteCount,
byte *arrayPointer);

Message Types
These are the various message types
that you can attach functions to.
ANALOG_MESSAGE

GSM library

the analog value for a single pin

The GSM library is included with Arduino


IDE 1.0.4 and later.
With the Arduino GSM Shield, this library
enables an Arduino board to do most of the
operations you can do with a GSM phone:
place and receive voice calls, send and
receive SMS, and connect to the internet
over a GPRS network.
The GSM shield has a modem that transfers
data from a serial port to the GSM network.
The modem executes operations via a
series of AT commands. The library
abstracts low level communications between
the modem and SIM card. It relies on
the Software Serial library for
communication between the moden and
Arduino.
Typically, each individual command is part
of a larger series necessary to execute a
particular function. The library can also
receive information and return it to you when
necessary.

DIGITAL_MESSAGE

8-bits of digital pin data (one port)


REPORT_ANALOG

enable/disable the reporting of analog


pin
REPORT_DIGITAL

enable/disable the reporting of a digital


port
SET_PIN_MODE

change the pin mode


between INPUT/OUTPUT/PWM/etc.
FIRMATA_STRING

C-style strings,
uses stringCallbackFunction for the function
type
SYSEX_START

generic, arbitrary length messages (via


MIDI SysEx protocol),
uses sysexCallbackFunction for the function
type
SYSTEM_RESET

Library structure

message to reset firmware to its default


state, uses systemResetCallbackFunction for
the function type

Example
This example shows how to send and
receive analog messages using
Firmata.

#include <Firmata.h>
byte analogPin;
void analogWriteCallback(byte pin, int value)
{
pinMode(pin,OUTPUT);
analogWrite(pin, value);
}
void setup()
{
Firmata.setFirmwareVersion(0, 1);
Firmata.attach(ANALOG_MESSAGE,
analogWriteCallback);
Firmata.begin();
}

As the library enables multiple types of


functionality, there are a number of different
classes.
The GSM class takes care of commands to
the radio modem. This handles the
connectivity aspects of the shield and
registers your system in the GSM
infrastructure. All of your GSM/GPRS
programs will need to include an object of
this class to handle the necessary low level
communication.
Voice call handling, managed by
the GSMVoiceCall class.
Send/receive SMS messages, managed by
the GSM_SMS class.
The GPRSClass is for connecting to the
internet.
GSMClient includes implementations for a
client, similar to the Ethernet
and WiFilibraries.
GSMServer includes implementations for a
server, similar to the Ethernet

and WiFilibraries. NB : A number of network


operators do not allow for incoming
connections from the public internet, but will
allow them from inside their own. Check with
your operator to see what restrictions there
are on data use.
A number of utility classes such
as GSMScanner and GSMModem

Ethernet library compatibility


The library tries to be as compatible as
possible with the current Ethernet library.
Porting a program from an Arduino Ethernet
or WiFi library to an Arduino with the GSM
Shield should be fairly easy. While it is not
possible to simply run Ethernet-compatible
code on the GSM shield as-is, some minor,
library specific, modifications will be
necessary, like including the GSM and
GPRS specific libraries and getting network
configuration settings from your cellular
network provider.
GSM class

This class prepares the functions that will


communicate with the modem.
GSM
begin()
shutdown()

GSMClient class

The client class creates clients that can


connect to servers and send and receive
data.

The Server class creates servers which can


send data to and receive data from
connected clients (programs running on
other computers or devices).

GSMVoiceCall class

Enables voice communication through the


modem. A microphone and speaker need to
be added for full use.

GSMVoiceCall
getVoiceCallStatus()
ready()
voiceCall()
answerCall()
hangCall()
retrieveCallingNumber()
GSM_SMS class

Facilitates sending and receiving Short


Message Service (SMS) messages.

GSM_SMS
beginSMS()
ready()
endSMS()
available()
remoteNumber()
read()
write()
print()
peek()
flush()
GPRS class

This class is responsible for including the


files that are part of the library that involve
TCP communication.
GPRS
attachGPRS()

GSMClient
ready()
connect()
beginWrite()
write()
endWrite()
connected()
read()
available()
peek()
flush()
stop()
GSMServer class

GSMServer
ready()
beginWrite()
write()
endWrite()
read()
available()
stop()
GSMModem class

The GSMModem class facilitates diagnostic


communication with the modem.
GSMModem
begin()
getIMEI()

GSMScanner class

The GSMScanner class provides diagnostic


information about the network and carrier.

GSMScanner
begin()
getCurrentCarrier()
getSignalStrength()
readNetworks()
GSMPIN class

The GSMPIN class has utilities for


communicating with the SIM card.

GSMPIN
begin()
isPIN()
checkPIN()
checkPUK()
changePIN()
switchPIN()
checkReg()
getPINUsed()
setPINUsed()
GSMBand class

The GSMBand class provides information


about the frequency band the modem

connects to. There are also methods for


setting the band.

// Nothing here
}

GSMBand
begin()
getBand()
setBand()

begin()

GSM constructor
Description
GSM is the base class for all GSM
based functions.
Syntax
GSM GSMAccess
GSM GSMAccess(debug)
Parameters
debug: boolean (default FALSE) flag
for turing on the debug mode. This will
print out the AT commands from the
modem.
Example
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
void setup()
{
// initialize serial communications
Serial.begin(9600);
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY){
notConnected = false;
Serial.println("Connected to network");
}
else
{
Serial.println("Not connected");
delay(1000);
}
}
}
void loop()
{

Description
Connects to the GSM network
identified on the SIM card.
Syntax
gsm.begin()
gsm.begin(pin)
gsm.begin(pin, restart)
gsm.begin(pin, restart, sync)
Parameters
pin : character array with the PIN to
access a SIM card (default = 0)
restart : boolean, determines whether
to restart modem or not (default= true)
sync : boolean, synchronous (true,
default) or asynchronous (false) mode
Returns
char : 0 if asynchronous. If
synchronous, returns status : ERROR,
IDLE, CONNECTING, GSM_READY,
GPRS_READY,
TRANSPARENT_CONNECTED
Example
#include <GSM.h>
#define PINNUMBER ""
GSM gsm; // include a 'true' parameter for debug
enabled
void setup()
{
// initialize serial communications
Serial.begin(9600);
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsm.begin(PINNUMBER)==GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}

Serial.println("GSM initialized");
}
void loop()
{
// once connected do something interesting
}

shutdown()
Description
Disconnects from the GSM network
identified on the SIM card by powering
the modem off.
Syntax
gsm.shutdown()
Parameters
none
Returns
boolean : 0 while executing, 1 when
successful
Example
#include <GSM.h>

{
}

GSMVoiceCall constructor
Description
GSMVoiceCall is the base class for all

GSM functions relating to receiving and


making voice calls.
GSM : GSMVoiceCall class

getVoiceCallStatus()
Description
Returns status of the voice call.
Syntax
voice.getVoiceCallStatus()
Parameters
none
Returns
char : IDLE_CALL, CALLING,
RECEIVINGCALL, TALKING
Example

#define PINNUMBER ""


GSM gsm; // include a 'true' parameter for debug
enabled
void setup()
{
// initialize serial communications
Serial.begin(9600);
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsm.begin(PINNUMBER)==GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
gsm.shutdown();
Serial.println("GSM terminated");
}
void loop()

// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMVoiceCall vcs;
char numtel[20];
call

// buffer for the incoming

void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Receive Voice Call");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{

Serial.println("Not connected");
delay(1000);

Description
Reports if the previous voice command
has executed successfully
Syntax
voice.ready()
Parameters
none
Returns
int
In asynchronous mode, ready() returns
0 if the last command is still executing,
1 if there is success, and >1 in case of
an error. In synchronous mode, it
returns 1 if it executed successfully, 0 if
not.

}
}
// This makes sure the modem notifies correctly
incoming events
vcs.hangCall();
Serial.println("Waiting Call");
}
void loop()
{
// Check the status of the voice call
switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL: // Nothing is happening
break;

GSM : GSMVoiceCall class

voiceCall()

case CALLING: // This should never happen,


as we are not placing a call
Serial.println("CALLING");
break;
case RECEIVINGCALL: // Yes! Someone is
calling us
Serial.println("RECEIVING CALL");
// Retrieve the calling number
vcs.retrieveCallingNumber(numtel, 20);
// Print the calling number
Serial.print("Number:");
Serial.println(numtel);
// Answer the call, establish the call
vcs.answerCall();
break;
case TALKING: // In this case the call would
be established
Serial.println("TALKING. Enter line to
interrupt.");
while(Serial.read()!='\n')
delay(100);
vcs.hangCall();
Serial.println("HANG. Waiting Call.");
break;
}
delay(1000);
}

GSM : GSMVoiceCall class

ready()

Description
Places a voice call to a specified
number. The methods returns different
information depending on the GSM
connection mode (synchronous or
asynchronous). See below for details.
Syntax
voice.voiceCall(number)
Parameters
number : char array. The number to
call.
Returns
int
In asynchronous mode, voiceCall()
returns 0 if last command is still
executing, 1 if successful, and >1 in
case of an error. In synchronous mode,
it returns 1 if the call is placed, 0 if not.
Example
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMVoiceCall vcs;
String remoteNumber = ""; // the number you
will call
char charbuffer[20];
void setup()
{

// initialize serial communications


Serial.begin(9600);
Serial.println("Make Voice Call");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized.");
Serial.println("Enter phone number to call.");

CallStatus()==TALKING));
// And hang up
vcs.hangCall();
}
Serial.println("Call Finished");
remoteNumber="";
Serial.println("Enter phone number to
call.");
}
else
{
Serial.println("That's too long for a phone
number. I'm forgetting it");
remoteNumber = "";
}
}
else
{
// add the latest character to the message to
send:
if(inChar!='\r')
remoteNumber += inChar;
}
}
}

answerCall()

}
void loop()
{
// add any incoming characters to the String:
while (Serial.available() > 0)
{
char inChar = Serial.read();
// if it's a newline, that means you should
make the call:
if (inChar == '\n')
{
// make sure the phone number is not too
long:
if (remoteNumber.length() < 20)
{
// let the user know you're calling:
Serial.print("Calling to : ");
Serial.println(remoteNumber);
Serial.println();
// Call the remote number
remoteNumber.toCharArray(charbuffer, 20)
;
// Check if the receiving end has picked up
the call
if(vcs.voiceCall(charbuffer))
{
Serial.println("Call Established. Enter line
to end");
// Wait for some input from the line
while(Serial.read() !='\n' && (vcs.getvoice

Description
Accepts an incoming voice call. The
method returns are different depending
on the modem mode (asynchronous or
synchronous), see below for details.
Syntax
voice.answerCall()
Parameters
none
Returns
int
In asynchronous mode, answerCall()
returns 0 if last command is still
executing, 1 if successful, and >1 in
case of an error. In synchronous mode,
it returns 1 if the call is answered, 0 if
not.
Example
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMVoiceCall vcs;
char numtel[20];
call

// buffer for the incoming

void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Receive Voice Call");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
// This makes sure the modem notifies correctly
incoming events
vcs.hangCall();
Serial.println("Waiting Call");
}
void loop()
{
// Check the status of the voice call
switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL: // Nothing is happening
break;
case CALLING: // This should never happen,
as we are not placing a call
Serial.println("CALLING");
break;
case RECEIVINGCALL: // Yes! Someone is
calling us
Serial.println("RECEIVING CALL");
// Retrieve the calling number
vcs.retrieveCallingNumber(numtel, 20);
// Print the calling number
Serial.print("Number:");
Serial.println(numtel);
// Answer the call, establish the call
vcs.answerCall();
break;

case TALKING: // In this case the call would


be established
Serial.println("TALKING. Enter line to
interrupt.");
while(Serial.read()!='\n')
delay(100);
vcs.hangCall();
Serial.println("HANG. Waiting Call.");
break;
}
delay(1000);
}

hangCall()
Description
Hang up an established call or during
incoming rings. Depending on the
modems mode (synchronous or
asynchronous) the method will return
differently, see below for more detail.
Syntax
voice.hangCall()
Parameters
none
Returns
int
In asynchronous mode, hangCall()
returns 0 if the last command is still
executing, 1 if there is success, and >1
in case of an error. In synchronous
mode, it returns 1 if the call is hung, 0 if
not.
Example
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMVoiceCall vcs;
char numtel[20];
call

// buffer for the incoming

void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Receive Voice Call");

// connection state
boolean notConnected = true;

delay(100);
vcs.hangCall();
Serial.println("HANG. Waiting Call.");
break;

// Start GSM shield


// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
// This makes sure the modem notifies correctly
incoming events
vcs.hangCall();
Serial.println("Waiting Call");
}
void loop()
{
// Check the status of the voice call
switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL: // Nothing is happening
break;
case CALLING: // This should never happen,
as we are not placing a call
Serial.println("CALLING");
break;
case RECEIVINGCALL: // Yes! Someone is
calling us
Serial.println("RECEIVING CALL");
// Retrieve the calling number
vcs.retrieveCallingNumber(numtel, 20);
// Print the calling number
Serial.print("Number:");
Serial.println(numtel);
// Answer the call, establish the call
vcs.answerCall();
break;
case TALKING: // In this case the call would
be established
Serial.println("TALKING. Enter line to
interrupt.");
while(Serial.read()!='\n')

}
delay(1000);
}

retrieveCallingNumber()

Description
Retrieves the calling number, and
stores it.
Syntax
voice.retrieveCallingNumber(number,
size)
Parameters
number : char array to hold the number
size : the size of the array
Returns
int
In asynchronous mode,
retrieveCallingNumber() returns 0 if the
last command is still executing, 1 if
success, and >1 if there is an error. In
synchronous mode, it returns 1 if the
number is obtained 0 if not.
Example
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMVoiceCall vcs;
char numtel[20];
call

// buffer for the incoming

void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Receive Voice Call");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;

else
{
Serial.println("Not connected");
delay(1000);
}
}
// This makes sure the modem notifies correctly
incoming events
vcs.hangCall();
Serial.println("Waiting Call");
}
void loop()
{
// Check the status of the voice call
switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL: // Nothing is happening
break;
case CALLING: // This should never happen,
as we are not placing a call
Serial.println("CALLING");
break;
case RECEIVINGCALL: // Yes! Someone is
calling us
Serial.println("RECEIVING CALL");
// Retrieve the calling number
vcs.retrieveCallingNumber(numtel, 20);
// Print the calling number
Serial.print("Number:");
Serial.println(numtel);
// Answer the call, establish the call
vcs.answerCall();
break;
case TALKING: // In this case the call would
be established
Serial.println("TALKING. Enter line to
interrupt.");
while(Serial.read()!='\n')
delay(100);
vcs.hangCall();
Serial.println("HANG. Waiting Call.");
break;
}
delay(1000);
}

GSM_SMS constructor

Description
GSM_SMS is the base class for all
GSM functions relating to receiving and
sending SMS messages.

beginSMS()
Description
Identifies the telephone number to send
an SMS message to.
Syntax
SMS.beginSMS(number)
Parameters
number : char array, the phone number
to send the SMS to
Returns
int
In asynchronous mode, beginSMS()
returns 0 if the last command is still
executing, 1 if success, and >1 if there
is an error. In synchronous mode, it
returns 1 if it successfully executes,
and 0 if it does not.
Example
#include <GSM.h>
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}

Serial.println("GSM initialized");
}
void loop()
{
Serial.print("Enter a mobile number: ");
char remoteNumber[20]; // telephone number
to send sms
readSerial(remoteNumber);
Serial.println(remoteNumber);
// sms text
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(remoteNumber);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
/*
Read input serial
*/
int readSerial(char result[])
{
int i = 0;
while(1)
{
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar == '\n')
{
result[i] = '\0';
Serial.flush();
return 0;
}
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
}
}
}

ready()
Description
Gets the status if the last GSMSMS
command.
Syntax
SMS.ready()

Parameters
none
Returns
int
In asynchronous mode, ready() returns
0 if the last command is still executing,
1 if it was successful, and >1 if there is
an error. In synchronous mode, it
returns 1 if the previous successfully
executed, and 0 if it has not.

endSMS()
Description
Tells the modem that the SMS
message is complete and sends it.
Syntax
SMS.endSMS()
Parameters
none
Returns
int
In asynchronous mode, endSMS()
returns 0 if it is still executing, 1 if
successful, and >1 if there is an error.
In synchronous mode, it returns 1 if the
previous successfully executed, and 0
if it has not.
Example
#include <GSM.h>
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;

else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop()
{
Serial.print("Enter a mobile number: ");
char remoteNumber[20]; // telephone number
to send sms
readSerial(remoteNumber);
Serial.println(remoteNumber);
// sms text
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(remoteNumber);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");

Description
Checks to see if there is a SMS
messages on the SIM card to be read,
and reports back the number of
characters in the message.
Syntax
SMS.available()
Parameters
none
Returns
int : the number of characters in the
message
Example
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;
char remoteNumber[20]; // Holds the emitting
number
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Receiver");
// connection state
boolean notConnected = true;

}
/*
Read input serial
*/
int readSerial(char result[])
{
int i = 0;
while(1)
{
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar == '\n')
{
result[i] = '\0';
Serial.flush();
return 0;
}
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
}
}
}

available()

// Start GSM shield


// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}
void loop()
{
char c;
// If there are any SMSs available()
if (sms.available())
{

Serial.println("Message received from:");


// Get remote number
sms.remoteNumber(remoteNumber, 20);
Serial.println(remoteNumber);
// This is just an example of message
disposal
// Messages starting with # should be
discarded
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}

// initialize the library instance


GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;
char remoteNumber[20]; // Holds the emitting
number
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Receiver");

// Read message bytes and print them


while(c=sms.read())
Serial.print(c);
Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");
}
delay(1000);
}

remoteNumber()

Description
Retrieves the phone number an from
an incoming SMS message and stores
it in a named array.
Syntax
SMS.remoteNumber(number, size)
Parameters
number : char array, a named array
that will hold the sender's number
size : int, the size of the array
Returns
int
In asynchronous mode,
remoteNumber() returns 0 if the last
command is still executing, 1 if
success, and >1 if there is an error. In
synchronous mode, it returns 1 if it
successfully executes, and 0 if it does
not.
Example
#include <GSM.h>
// PIN Number
#define PINNUMBER ""

// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}
void loop()
{
char c;
// If there are any SMSs available()
if (sms.available())
{
Serial.println("Message received from:");
// Get remote number
sms.remoteNumber(remoteNumber, 20);
Serial.println(remoteNumber);
// This is just an example of message
disposal
// Messages starting with # should be
discarded
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}
// Read message bytes and print them

while(c=sms.read())
Serial.print(c);

notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}

Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");

}
delay(1000);
}

read()
Description
Reads a byte from an SMS message.
read() inherits from the Stream utility
class.
Syntax
SMS.read()
Parameters
none
Returns
int - the first byte of incoming serial
data available (or -1 if no data is
available)
Example
#include <GSM.h>
// PIN Number
#define PINNUMBER ""

Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}
void loop()
{
char c;
// If there are any SMSs available()
if (sms.available())
{
Serial.println("Message received from:");
// Get remote number
sms.remoteNumber(remoteNumber, 20);
Serial.println(remoteNumber);
// This is just an example of message
disposal
// Messages starting with # should be
discarded
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}
// Read message bytes and print them
while(c=sms.read())
Serial.print(c);

// initialize the library instance


GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;

Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");

char remoteNumber[20]; // Holds the emitting


number
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Receiver");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)

}
delay(1000);
}

write()
Description
Writes a character to a SMS message.
Syntax
SMS.write(val)
Parameters
val: a character to send in the message

Returns
byte - write() will return the number of
bytes written, though reading that
number is optional
Example
#include <GSM.h>
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop()
{
Serial.print("Enter a mobile number: ");
char remoteNumber[20]; // telephone number
to send sms
readSerial(remoteNumber);
Serial.println(remoteNumber);
// sms text
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);

// send the message


sms.beginSMS(remoteNumber);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
/*
Read input serial
*/
int readSerial(char result[])
{
int i = 0;
while(1)
{
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar == '\n')
{
result[i] = '\0';
Serial.flush();
return 0;
}
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
}
}
}

peek()
Description
Returns the next byte (character) of an
incoming SMS without removing it from
the message. That is, successive calls
to peek() will return the same
character, as will the next call to read().
peek() inherits from the Stream utility
class.
Syntax
SMS.peek()
Parameters
none
Returns
int - the first byte available of a SMS
message (or -1 if no data is available)
Example
/*
SMS receiver
This sketch, for the Arduino GSM shield, waits
for SMS messages
and displays them through the Serial port.
Circuit:

* GSM shield
created 25 Feb 2012
by Javier Zorzano / TD
This example is in the public domain.
*/
// libraries
#include <GSM.h>

Serial.println(remoteNumber);
// This is just an example of message
disposal
// Messages starting with # should be
discarded
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}

// PIN Number
#define PINNUMBER ""

// Read message bytes and print them


while(c=sms.read())
Serial.print(c);

// initialize the library instance


GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;

Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");

char remoteNumber[20]; // Holds the emitting


number
}
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Receiver");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}
void loop()
{
char c;
// If there are any SMSs available()
if (sms.available())
{
Serial.println("Message received from:");
// Get remote number
sms.remoteNumber(remoteNumber, 20);

delay(1000);
}

flush()
Description
flush() clears the modem memory of
any sent messages once all outgoing
characters have been sent. flush()
inherits from the Stream utility class.
Syntax
SMS.flush()
Parameters
none
Returns
none
Example
/*
SMS receiver
This sketch, for the Arduino GSM shield, waits
for SMS messages
and displays them through the Serial port.
Circuit:
* GSM shield
created 25 Feb 2012
by Javier Zorzano / TD
This example is in the public domain.
*/
// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// Read message bytes and print them


while(c=sms.read())
Serial.print(c);

// initialize the library instance


GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;

Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");

char remoteNumber[20]; // Holds the emitting


number
}
void setup()
{
// initialize serial communications
Serial.begin(9600);

delay(1000);
}

Serial.println("SMS Messages Receiver");

GPRS constructor

// connection state
boolean notConnected = true;

Description
GPRS is the base class for all GPRS
functions, such as internet client and
server behaviors.

// Start GSM shield


// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}

attachGPRS()

Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}
void loop()
{
char c;
// If there are any SMSs available()
if (sms.available())
{
Serial.println("Message received from:");
// Get remote number
sms.remoteNumber(remoteNumber, 20);
Serial.println(remoteNumber);
// This is just an example of message
disposal
// Messages starting with # should be
discarded
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}

Description
Connects to the specified Access Point
Name (APN) to initiate GPRS
communication.
Every cellular provider has an Access
Point Name (APN) that serves as a
bridge between the cellular network
and the internet. Sometimes, there is a
username and password associated
with the connection point. For example,
the Bluevia APN is bluevia.movistar.es,
but it has no password or login name.
This page lists a number of carrier's
information, but it may not be up to
date. You may need to get this
information from your service provider.
Syntax
grps.attachGPRS(APN, user,
password)
Parameters
APN : char array, the Access Point
Name (APN) provided by the mobile
operator
user : char array, the username for the
APN
password : char array, the password to
access the APN
Returns
char array : ERROR, IDLE,
CONNECTING, GSM_READY,

GPRS_READY,
TRANSPARENT_CONNECTED
Example
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" // replace
your GPRS APN
#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GPRS gprs;
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMServer server(80); // port 80 (http default)
// timeout
const unsigned long __TIMEOUT__ = 10*1000;
void setup()
{
// initialize serial communications
Serial.begin(9600);
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("Connected to GPRS network");
// start server
server.begin();
//Get IP.
IPAddress LocalIP = gprs.getIPAddress();
Serial.println("Server IP address=");
Serial.println(LocalIP);
}

void loop() {
// listen for incoming clients
GSM3MobileClientService
client = server.available();

if (client)
{
while (client.connected())
{
if (client.available())
{
Serial.println("Receiving request!");
bool sendResponse = false;
while(char c=client.read()) {
if (c == '\n') sendResponse = true;
}
// if you've gotten to the end of the line
(received a newline
// character)
if (sendResponse)
{
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
// output the value of each analog input
pin
for (int analogChannel = 0; analogChanne
l < 6; analogChannel++) {
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(analogRead(analogChannel))
;
client.println("<br />");
}
client.println("</html>");
//necessary delay
delay(1000);
client.stop();
}
}
}
}
}

GSM : Client class

Client
Description
Client is the base class for all GPRS
client based calls. It is not called
directly, but invoked whenever you use
a function that relies on it.

#include <GSM.h>

ready()
Description
Gets the status of the last command
Syntax
client.ready()
Parameters
none
Returns
In asynchronous mode, ready() returns
0 if the last command is still executing,
1 if it was successful, and >1 if there is
an error. In synchronous mode, it
returns 1 if the previous successfully
executed, and 0 if it has not.

connect()

Description
Connects to a specified IP address and
port. The return value indicates
success or failure.
Syntax
client.connect(ip, port)
Parameters
ip: the IP address that the client will
connect to (array of 4 bytes)
port: the port that the client will connect
to (int)
Returns
boolean : Returns true if the connection
succeeds, false if not.
Example
/*
Web client
This sketch connects to a website through a
GSM shield. Specifically,
this example downloads the URL
"http://arduino.cc/" and prints it
to the Serial monitor.
Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan
created 8 Mar 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/GSMExamplesWeb
Client
*/
// libraries

// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" // replace
your GPRS APN
#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;
// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/";
int port = 80; // port 80 is the default for HTTP
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Starting Arduino web client.");
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with
the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port))
{
Serial.println("connected");
// Make a HTTP request:
client.print("GET ");
client.print(path);
client.println(" HTTP/1.0");
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.available() && !client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
for(;;)
;
}
}

beginWrite()
Description
Tells the client to start writing to the
server it is connected to.
Syntax
client.beginWrite()
Parameters
none
Returns
none

write()

Description
Write data to the server the client is
connected to.
Syntax
client.write(data)
client.write(buffer)
client.write(buffer, size)
Parameters
data: the value to write (byte or char)
buffer : an array of data (byte or char)
to write
size : size of the buffer to write (byte)

Returns
byte - write() returns the number of
bytes written. It is not necessary to
read this.

endWrite()
Description
Stops writing data to a server
Syntax
client.endWrite()
Parameters
none
Returns
none

connected()
Description
Returns whether or not the client is
connected. A client is considered
connected if the connection has been
closed but there is still unread data.
Syntax
client.connected()
Parameters
none
Returns
boolean - Returns true if the client is
connected, false if not.
Example
/*
Web client
This sketch connects to a website through a
GSM shield. Specifically,
this example downloads the URL
"http://arduino.cc/" and prints it
to the Serial monitor.
Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan
created 8 Mar 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/GSMExamplesWeb
Client
*/
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN
"GPRS_APN" // replace
your GPRS APN
#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

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.available() && !client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();

// URL, path & port (for example: arduino.cc)


char server[] = "arduino.cc";
char path[] = "/";
int port = 80; // port 80 is the default for HTTP
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Starting Arduino web client.");
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with
the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port))
{
Serial.println("connected");
// Make a HTTP request:
client.print("GET ");
client.print(path);
client.println(" HTTP/1.0");
client.println();
}
else
{
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}

// do nothing forevermore:
for(;;)
;
}
}

read()
Description
Read the next byte received from the
server the client is connected to (after
the last call to read()).
read() inherits from the Stream utility
class.
Syntax
client.read()
Parameters
none
Returns
int - The next byte (or character), or -1
if none is available.
Example
/*
Web client
This sketch connects to a website through a
GSM shield. Specifically,
this example downloads the URL
"http://arduino.cc/" and prints it
to the Serial monitor.
Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan
created 8 Mar 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/GSMExamplesWeb
Client

*/

}
else
{
// if you didn't get a connection to the server:
Serial.println("connection failed");
}

// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" // replace
your GPRS APN
#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

}
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.available() && !client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();

// URL, path & port (for example: arduino.cc)


char server[] = "arduino.cc";
char path[] = "/";
int port = 80; // port 80 is the default for HTTP
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Starting Arduino web client.");
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with
the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port))
{
Serial.println("connected");
// Make a HTTP request:
client.print("GET ");
client.print(path);
client.println(" HTTP/1.0");
client.println();

// do nothing forevermore:
for(;;)
;
}
}

available()
Description
Returns the number of bytes available
for reading (that is, the amount of data
that has been written to the client by
the server it is connected to).
available() inherits from
the Stream utility class.
Syntax
client.available()
Parameters
none
Returns
The number of bytes available.
Example
/*
Web client
This sketch connects to a website through a
GSM shield. Specifically,
this example downloads the URL
"http://arduino.cc/" and prints it
to the Serial monitor.
Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan

{
created 8 Mar 2012
by Tom Igoe

Serial.println("connected");
// Make a HTTP request:
client.print("GET ");
client.print(path);
client.println(" HTTP/1.0");
client.println();

http://arduino.cc/en/Tutorial/GSMExamplesWeb
Client
*/

}
else
{
// if you didn't get a connection to the server:
Serial.println("connection failed");
}

// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" // replace
your GPRS APN
#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

}
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.available() && !client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();

// URL, path & port (for example: arduino.cc)


char server[] = "arduino.cc";
char path[] = "/";
int port = 80; // port 80 is the default for HTTP
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Starting Arduino web client.");
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with
the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port))

// do nothing forevermore:
for(;;)
;
}
}

peek()
Description
Returns the next byte (character) of an
incoming message removing it from the
message. That is, successive calls to
peek() will return the same character,
as will the next call to read(). peek()
inherits from the Stream utility class.
Syntax
client.peek()
Parameters
none
Returns
int - the next byte in an incoming
message.

flush()

Description
Discards any bytes that have been
written to the client but not yet read.
flush() inherits from the Stream utility
class.
Syntax
client.flush()
Parameters
none
Returns
none

stop()
Description
Disconnects from the server
Syntax
client.stop()
Parameters
none
Returns
none
Example
/*
Web client
This sketch connects to a website through a
GSM shield. Specifically,
this example downloads the URL
"http://arduino.cc/" and prints it
to the Serial monitor.

// initialize the library instance


GSMClient client;
GPRS gprs;
GSM gsmAccess;
// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/";
int port = 80; // port 80 is the default for HTTP
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Starting Arduino web client.");
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with
the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("connecting...");

Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan

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


if (client.connect(server, port))
{
Serial.println("connected");
// Make a HTTP request:
client.print("GET ");
client.print(path);
client.println(" HTTP/1.0");
client.println();
}
else
{
// if you didn't get a connection to the server:
Serial.println("connection failed");
}

created 8 Mar 2012


by Tom Igoe
http://arduino.cc/en/Tutorial/GSMExamplesWeb
Client
*/
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" // replace
your GPRS APN
#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password

}
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.available() && !client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
for(;;)
;
}
}

Server
Description
Server is the base class for all GPRS
server based calls. It is not called
directly, but invoked whenever you use
a function that relies on it.
Syntax
GSMServer server(port);
Parameters
port: int, the port the server will accept
connections on. The default web port is
80.

ready()
Description
Get last command status to the server
Syntax
server.ready()
Parameters
none
Returns
int - 0 if last command is still executing,
1 if success, >1 if an error.

beginWrite()
Description
Begins writing to connected clients.
Syntax
server.beginWrite()
Parameters
none
Returns
none

write()

Description
Write data to all the clients connected
to a server.
Syntax
server.write(data)
server.write(buffer)
server.write(buffer, size)
Parameters
data: the value to write (byte or char)
buffer : an array of data (byte or char)
to write
size : size of the buffer to write (byte)
Returns
byte - write() returns the number of
bytes written. It is not necessary to
read this.

endWrite()
Description
Tells the server to stop writing to
connected clients.
Syntax
server.endWrite()
Parameters
none
Returns
none

read()
Description
Read the next byte received from an
attached client (after the last call to
read()).
read() inherits from the Stream utility
class.
Syntax
server.read()
Parameters
none
Returns
int - The next byte (or character), or -1
if none is available.

available()
Description
Listens for incoming clients
Syntax
server.available()
Parameters
none

Returns
int : the number of connected clients

// modem verification object


GSMModem modem;

GSMModem Constructor

// IMEI variable
String IMEI = "";

Description
GSMModem is the base class for calls
that have specific diagnostic
functionality with the modem. It is not
called directly, but invoked whenever
you use a function that relies on it.
Functions
begin()
getIMEI()
Reference Home
Corrections, suggestions, and new
documentation should be posted to
the Forum.
The text of the Arduino reference is
licensed under a Creative Commons
Attribution-ShareAlike 3.0 License.
Code samples in the reference are
released into the public domain.

begin()
Description
Checks the modem status, and restarts
it. Call this
before GSMModem.getIMEI().
Syntax
modem.begin()
Parameters
none
Returns
int : returns 1 if modem is OK,
otherwise returns an error.

getIMEI()
Description
Retrieves the modem's IMEI number.
Call this after GSMModem.begin().
Syntax
modem.getIMEI()
Parameters
none
Returns
String : the modem's IMEI number
Example
// libraries
#include <GSM.h>

void setup()
{
// initialize serial communications
Serial.begin(9600);
// start modem test (reset and check response)
Serial.print("Starting modem test...");
if(modem.begin())
Serial.println("modem.begin() succeeded");
else
Serial.println("ERROR, no modem answer.");
}
void loop()
{
// get modem IMEI
Serial.print("Checking IMEI...");
IMEI = modem.getIMEI();
// check IMEI response
if(IMEI != NULL)
{
// show IMEI in serial monitor
Serial.println("Modem's IMEI: " + IMEI);
// reset modem to check booting:
Serial.print("Reseting modem...");
modem.begin();
// get and check IMEI one more time
if(modem.getIMEI() != NULL)
{
Serial.println("Modem is functoning
properly");
}
else
{
Serial.println("Error: getIMEI() failed after
modem.begin()");
}
}
else
{
Serial.println("Error: Could not get IMEI");
}
// do nothing:
while(true);
}

GSMScanner Constructor
Description
GSMScanner is the base class for calls
that have specific diagnostic
functionality relating to scanning for
available networks. It is not called

directly, but invoked whenever you use


a function that relies on it.

begin()
Description
Resets modem hardware.
Syntax
scanner.begin()
Parameters
none
Returns
int : returns 1 if modem is OK,
otherwise returns an error.

getCurrentCarrier()
Description
Gets and returns the name of the
current network carrier.
Syntax
scanner.getCurrentCarrier()
Parameters
none
Returns
String : name of the current network
carrier

getSignalStrength()
Description
Gets and returns the strength of the
signal of the network the modem is
attached to.
Syntax
scanner.getSignalStrength()
Parameters
none
Returns
String : signal strength in 0-31 scale. 31
means power > 51dBm. 99=not
detectable

readNetworks()
Description
Searches for available carriers, and
returns a list of them.
Syntax
scanner.readNetworks()
Parameters
none

Returns
String : A string with list of networks
available

GSMPIN constructor
Description
GSMPIN is the base class for all GSM
based functions that deal with
interacting with the PIN on the SIM
card.

begin()
Description
Checks the modem status, and restarts
it.
Syntax
GSMPIN.begin()
Parameters
none
Returns
int : returns 1 if modem is OK,
otherwise returns an error.

isPIN()
Description
Checks the SIM card to see if it is
locked with a PIN.
Syntax
pin.isPIN()
Parameters
none
Returns
int : 0 if PIN lock is off, 1 if PIN lock is
on, -1 if PUK lock is on, -2 if error
exists.

checkPIN()
Description
Queries the SIM card with a PIN
number to see if it is valid.
Syntax
pin.checkPIN(PIN)
Parameters
PIN : String with the PIN number to
check
Returns
int : Returns 0 if the PIN is valid,
returns -1 if it is not.

checkPUK()

Description
Check the SIM if PUK code is correct
and establish new PIN code.
Syntax
pin.checkPUK(puk, pin)
Parameters
puk : String with the PUK number to
check
pin : String with the PIN number to
check
Returns
int : Returns 0 if successful, -1 if it is
not.

Parameters
Returns
int : 0 if modem was registered, 1 if
modem was registered in roaming, -1 if
error exists

getPinUsed()
Description
Check if PIN lock is used.
Syntax
pin.getPinUsed()
Parameters
Returns
boolean : TRUE id locked, FALSE if not

changePIN()

setPinUsed()

Description
Changes the PIN number of a SIM,
after verifying the existing one.
Syntax
pin.changePIN(oldPIN, newPIN)
Parameters
oldPIN : String with the existing PIN
number newPIN : String with the
desired PIN number
Returns
none

GSMBand Constructor

switchPIN()
Description
Change PIN lock status.
Syntax
pin.switchPIN(pin)
Parameters
pin : String with the existing PIN
number
Returns
none

checkReg()
Description
Check if modem was registered in
GSM/GPRS network
Syntax
pin.checkReg()

Description
Set PIN lock status.
Syntax
pin.setPinUsed(used)
Parameters
used : boolean, TRUE to lock the PIN,
FALSE to unlock.
Returns
none

Description
GSMBand is the base class for calls
that have specific diagnostic
functionality relating to the bands the
modem can connect to. It is not called
directly, but invoked whenever you use
a function that relies on it.

begin()
Description
Checks the modem status, and restarts
it.
Syntax
band.begin()
Parameters
none
Returns
int : returns 1 if modem is OK,
otherwise returns an error.

getBand()

Description
Gets and returns the frequency band
the modem is currently connected to.
Checkhttp://www.worldtimezone.com/g
sm.html for general GSM band
information. Typical regional
configurations are :
Europe, Africa, Middle East: EGSM(900)+DCS(1800)
USA, Canada, South America:
GSM(850)+PCS(1900)
Mexico: PCS(1900)
Brazil: GSM(850)+EGSM(900)+DCS(1800)+PCS(1900)
Syntax
band.getBand()
Parameters
none
Returns
String : name of the frequency band the
modem connects to
GSM_MODE_UNDEFINED
GSM_MODE_EGSM
GSM_MODE_DCS
GSM_MODE_PCS
GSM_MODE_EGSM_DCS
GSM_MODE_GSM850_PCS
GSM_MODE_GSM850_EGSM_DCS_
PCS

setBand()

Description
Sets the frequency band the modem
connects to.
Check http://www.worldtimezone.com/g
sm.html for general GSM band
information. Typical regional
configurations are :
Europe, Africa, Middle East: EGSM(900)+DCS(1800)
USA, Canada, South America:
GSM(850)+PCS(1900)
Mexico: PCS(1900)
Brazil: GSM(850)+EGSM(900)+DCS(1800)+PCS(1900)
Syntax
band.setBand(type)
Parameters
type : String identifying what frequency
band the modem should connect to :

GSM_MODE_UNDEFINED
GSM_MODE_EGSM
GSM_MODE_DCS
GSM_MODE_PCS
GSM_MODE_EGSM_DCS
GSM_MODE_GSM850_PCS
GSM_MODE_GSM850_EGSM_DCS_
PCS
Returns
boolean : returns true if the process is
successful, false if it is not
Make Voice Call
This sketch connects a voice call from
your GSM shield and Arduino to a
remote phone number entered through
the serial monitor. You'll need to attach
a speaker and microphone to hear the
connected phone and send your voice.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
Microphone and speaker attached to
the GSM shield
SIM card
Circuit

phone number to the Arduino. After


opening the connection, send a
message to the Serial Monitor
indicating the sketch has started.
void setup(){
Serial.begin(9600);
Serial.println("Make Voice Call");
[Get Code]

Create a local variable to track the


connection status. You'll use this to
keep the sketch from starting until the
SIM is connected to the network :
boolean notConnected = true;
[Get Code]

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. By placing
this inside a while() loop, you can
continually check the status of the
connection. When the modem does
connect, gsmAccess()will
return GSM_READY. Use this as a flag to
set the notConnected variable to true or false.
Once connected, the remainder
of setup will run.

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

SIM cards may have a PIN number that


unlocks their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Initialize instances of the classes you're


going to use. You're going to need both
the GSM and GSMVoiceCall class.
GSM gsmAccess;
GSMVoiceCall vcs;
[Get Code]

Create some variables to store the


phone number you want to call :
String remoteNumber = "";
char charbuffer[20];
[Get Code]

In setup, open a serial connection to the


computer. You'll use this to send a

while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]

Finish setup with some information to the


serial monitor.
Serial.println("GSM initialized.");
Serial.println("Enter phone number to call.");
}
[Get Code]

The loop will accept incoming bytes from


the serial monitor and connect your
voice call.
First, check the serial buffer to see if
there is any information waiting to be
read. If there is, store it in a local
variable :
void loop()
{
while (Serial.available() > 0)

{
char inChar = Serial.read();
[Get Code]

If the buffer holds a newline character,


check to see if the number entered is
less than 20 digits long (theoretically,
you'll never be able to dial a number
with more digits than that).
if (inChar == '\n')
{
if (remoteNumber.length() < 20)
{
[Get Code]

Print out the number you're calling to


the serial monitor.
Serial.print("Calling to : ");
Serial.println(remoteNumber);
Serial.println();
[Get Code]

The number to call will be been stored


in the String named remoteNumber.
The voiceCall() function requires
a chararray. Copy the string to the array
named charbuffer.
remoteNumber.toCharArray(charbuffer, 20);

To place the call, use vcs.voiceCall(),


passing it the number you wish to
reach. voiceCall() returns the status of the
call; a 1 means it is connected. You can
check the status of the connection
with getvoiceCallStatus().
To disconnect your call, send a newline
character to trigger hangCall().
if(vcs.voiceCall(charbuffer))
{
Serial.println("Call Established. Enter line
to end");
while(Serial.read()!='\n' && (vcs.getvoiceC
allStatus()==TALKING));
vcs.hangCall();
}
[Get Code]

Once the call has been completed,


clear the variable that stored the phone
number :
Serial.println("Call Finished");
remoteNumber="";
Serial.println("Enter phone number to
call.");
}
[Get Code]

Serial.println("That's too long for a phone


number. I'm forgetting it");
remoteNumber = "";
}
}
[Get Code]

When reading information from the


serial monitor, if the incoming character
is not a newline or carriage return, add
it to the remoteNumber String and close up
the loop.
else
{
// add the latest character to the message to
send:
if(inChar!='\r')
remoteNumber += inChar;
}
}
}
[Get Code]

Once your code is uploaded, open the


serial monitor. Once you see the
message "Enter phone number to call",
type a phone number and press
"return". Make sure the serial monitor is
set to only send a newline character on
return.
/*
Make Voice Call
This sketch, for the Arduino GSM shield, puts a
voice call to
a remote phone number that you enter through
the serial monitor.
To make it work, open the serial monitor, and
when you see the
READY message, type a phone number. Make
sure the serial monitor
is set to send a just newline when you press
return.
Circuit:
* GSM shield
* Voice circuit.
With no voice circuit the call will send nor
receive any sound
created Mar 2012
by Javier Zorzano
This example is in the public domain.
*/

If the number you entered in the serial


monitor is longer than 20 digits, clear
the remoteNumber String and start again :

// libraries
#include <GSM.h>

else
{

// PIN Number

#define PINNUMBER ""

// let the user know you're calling:


Serial.print("Calling to : ");
Serial.println(remoteNumber);
Serial.println();

// initialize the library instance


GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMVoiceCall vcs;

// Call the remote number


remoteNumber.toCharArray(charbuffer, 20)

String remoteNumber = ""; // the number you


will call
char charbuffer[20];

;
// Check if the receiving end has picked up
the call
if(vcs.voiceCall(charbuffer))
{
Serial.println("Call Established. Enter line
to end");
// Wait for some input from the line
while(Serial.read()!='\n' && (vcs.getvoiceC
allStatus()==TALKING));
// And hang up
vcs.hangCall();
}
Serial.println("Call Finished");
remoteNumber="";
Serial.println("Enter phone number to
call.");
}
else
{
Serial.println("That's too long for a phone
number. I'm forgetting it");
remoteNumber = "";
}
}
else
{
// add the latest character to the message to
send:
if(inChar!='\r')
remoteNumber += inChar;
}
}
}

void setup()
{
// initialize serial communications and wait for
port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
Serial.println("Make Voice Call");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized.");
Serial.println("Enter phone number to call.");
}
void loop()
{
// add any incoming characters to the String:
while (Serial.available() > 0)
{
char inChar = Serial.read();
// if it's a newline, that means you should
make the call:
if (inChar == '\n')
{
// make sure the phone number is not too
long:
if (remoteNumber.length() < 20)
{

Receive Voice Call


This sketch receives a voice call from
an Arduino with a connected GSM
shield. Once connected, it shows the
number that is calling, and hangs up.
You'll need to attach a speaker and
microphone to hear the connected call
and send your voice.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
Microphone and speaker attached to
the GSM shield

SIM card
Circuit

In setup, open a serial connection to the


computer. After opening the
connection, send a message indicating
the sketch has started.
void setup(){
Serial.begin(9600);
Serial.println("Receive Voice Call");
[Get Code]

Create a local variable to track the


connection status. You'll use this to
keep the sketch from starting until the
SIM is connected to the network :
boolean notConnected = true;
[Get Code]

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. By placing
this inside a while() loop, you can
continually check the status of the
connection. When the modem does
connect, gsmAccess()will
return GSM_READY. Use this as a flag to
set the notConnected variable to true or false.
Once connected, the remainder
of setup will run.

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

SIM cards may have a PIN number that


unlocks their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Initialize instances of the classes you're


going to use. You're going to need both
the GSM and GSMVoiceCall class.
GSM gsmAccess;
GSMVoiceCall vcs;
[Get Code]

Create a char array to store the


incoming number :
char numtel[20];
[Get Code]

while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]

To ensure the modem is ready to


accept incoming calls, use
the hangCall() function
vcs.hangCall();

Finish setup with some information to the


serial monitor.
Serial.println("GSM initialized.");
Serial.println("Awaiting call.");
}
[Get Code]

In loop, use a switch statement to control


the flow of the
program. getvoiceCallStatus() will return its
state when it is called.
void loop()
{
switch (vcs.getvoiceCallStatus())
{

[Get Code]

If getvoiceCallStatus() returns IDLE_CALL,


there is nothing happening.
case IDLE_CALL:
break;
[Get Code]

If getvoiceCallStatus() returns RECEIVINGCALL,


someone is calling you.
Use retrieveCallingNumber() to store the
incoming number to the numtel array you
created, and print it to the serial
monitor.
Use answerCall() to initiate the voice
conection with the caller.
case RECEIVINGCALL:
Serial.println("RECEIVING CALL");
vcs.retrieveCallingNumber(numtel, 20);
Serial.print("Number:");
Serial.println(numtel);
vcs.answerCall();
break;
[Get Code]

Once you have answered the


call, getvoiceCallStatus() will return TALKING.
The sketch will wait for a newline
character to trigger hangCall() and
terminate the connection.
Close the switch statement.

receives voice calls,


displays the calling number, waits a few
seconds and gently hangs,
Circuit:
* GSM shield
* Voice circuit.
With no voice circuit the call will send nor
receive any sound
created Mar 2012
by Javier Zorzano
This example is in the public domain.
*/
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMVoiceCall vcs;
char numtel[20];
call

void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Receive Voice Call");

case TALKING:
Serial.println("TALKING. Enter line to
interrupt.");
while(Serial.read()!='\n')
delay(100);
vcs.hangCall();
Serial.println("HANG. Waiting Call.");
break;
}
[Get Code]

Add a small delay before continuing


with the loop:
delay(1000);
}
[Get Code]

Once your code is uploaded, open the


serial monitor. Make sure the serial
monitor is set to only send a newline
character on return.

// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
// This makes sure the modem notifies correctly
incoming events
vcs.hangCall();

/*
Receive Voice Call

Serial.println("Waiting Call");
}

This sketch, for the Arduino GSM shield,

// buffer for the incoming

void loop()
{
// Check the status of the voice call
switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL: // Nothing is happening
break;
case CALLING: // This should never happen,
as we are not placing a call
Serial.println("CALLING");
break;
case RECEIVINGCALL: // Yes! Someone is
calling us
Serial.println("RECEIVING CALL");
// Retrieve the calling number
vcs.retrieveCallingNumber(numtel, 20);
// Print the calling number
Serial.print("Number:");
Serial.println(numtel);
// Answer the call, establish the call
vcs.answerCall();
break;
case TALKING: // In this case the call would
be established
Serial.println("TALKING. Enter line to
interrupt.");
while(Serial.read()!='\n')
delay(100);
vcs.hangCall();
Serial.println("HANG. Waiting Call.");
break;
}
delay(1000);
}

Send SMS
This sketch send a SMS message from
an Arduino with a connected GSM
shield. using the serial monitor, you'll
enter the number to connect with, and
the message to send.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card
Circuit

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

SIM cards may have a PIN number that


enables their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Initialize instances of the classes you're


going to use. You're going to need both
the GSM and GSM_SMS class.
GSM gsmAccess;
GSM_SMS sms;
[Get Code]

In setup, open a serial connection to the


computer. After opening the
connection, send a message indicating
the sketch has started.
void setup(){
Serial.begin(9600);
Serial.println("SMS Messages Sender");

[Get Code]

Create a local variable to track the


connection status. You'll use this to
keep the sketch from starting until the
SIM is connected to the network :
boolean notConnected = true;
[Get Code]

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. By placing
this inside a while() loop, you can
continually check the status of the
connection. When the modem does
connect, gsmAccess()will
return GSM_READY. Use this as a flag to
set the notConnected variable
to true or false. Once connected, the
remainder of setup will run.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]

Finish setup with some information to the


serial monitor.
Serial.println("GSM initialized.");
}
[Get Code]

Create a function named readSerial of


type int. You'll use this to iterate through
input from the serial monitor, storing
the number you wish to send an SMS
to, and the message you'll be sending.
It should accept a char array as an
argument.
int readSerial(char result[])
{
[Get Code]

Create a variable to count through the


items in the serial buffer, and start
a while loop that will continually execute.
int i = 0;
while(1)
{
[Get Code]

As long as there is serial information


available, read the data into a variable
named inChar.

while (Serial.available() > 0)


{
char inChar = Serial.read();
[Get Code]

If the character being read is a newline,


terminate the array, clear the serial
buffer and exit the function.
if (inChar == '\n')
{
result[i] = '\0';
Serial.flush();
return 0;
}
[Get Code]

If the incoming character is an ASCII


character other than a newline or
carriage return, add it to the array and
increment the index. Close up
the while loops and the function.
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
}
}
}
[Get Code]

In loop, create a char array


named remoteNumber to hold the number
you wish to send an SMS to. Invoke
thereadSerial function you just created,
and pass remoteNumber as the argument.
When readSerial executes, it will
populate remoteNumber with the number
you wish to send the message to.
Serial.print("Enter a mobile number: ");
char remoteNumber[20];
readSerial(remoteNumber);
Serial.println(remoteNumber);
[Get Code]

Create a new char array named txtMsg.


This will hold the content of your SMS.
Pass txtMsg to readSerial to populate the
array.
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
[Get Code]

Call sms.beginSMS() and pass


it remoteNumber to start sending the
message, sms.print() to send the
message, andsms.endSMS() to complete
the process. Print out some diagnostic

Serial.println("SMS Messages Sender");

information and close the loop. Your


message is on its way!
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
sms.beginSMS(remoteNumber);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
[Get Code]

Once your code is uploaded, open the


serial monitor. Make sure the serial
monitor is set to only send a newline
character on return. When prompted to
enter the number you wish to call, enter
the digits and press return. You'll then
be asked to enter your message. Once
you've typed that, press return again to
send it.
/*
SMS sender
This sketch, for the Arduino GSM shield,sends
an SMS message
that you send it through the serial monitor. To
make it work,
open the serial monitor, and when you see the
READY message,
type a message to send. Make sure the serial
monitor is set
to send a newline when you press return.

// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop()
{
Serial.print("Enter a mobile number: ");
char remoteNumber[20]; // telephone number
to send sms
readSerial(remoteNumber);
Serial.println(remoteNumber);
// sms text
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);

Circuit:
* GSM shield
created 25 Feb 2012
by Tom Igoe

// send the message


sms.beginSMS(remoteNumber);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");

This example is in the public domain.


*/
// libraries
#include <GSM.h>
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;
void setup()
{
// initialize serial communications
Serial.begin(9600);

}
/*
Read input serial
*/
int readSerial(char result[])
{
int i = 0;
while(1)
{
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar == '\n')
{
result[i] = '\0';

Serial.flush();
return 0;
}
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
}
}
}

Receive SMS
This sketch waits for a SMS message
and prints it to the serial monitor. It
requires an Arduino with a connected
GSM shield and SIM card.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card
Circuit

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

SIM cards may have a PIN number that


enables their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Initialize instances of the classes you're


going to use. You're going to need both
the GSM and GSM_SMS class.
GSM gsmAccess;
GSM_SMS sms;
[Get Code]

Create a char array to hold the number


that is sending the message :
char remoteNumber[20];

In setup, open a serial connection to the


computer. After opening the
connection, send a message indicating
the sketch has started.

void setup(){
Serial.begin(9600);
Serial.println("SMS Messages Receiver");
[Get Code]

Create a local variable to track the


connection status. You'll use this to
keep the sketch from starting until the
SIM is connected to the network :
boolean notConnected = true;
[Get Code]

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. By placing
this inside a while() loop, you can
continually check the status of the
connection. When the modem does
connect, gsmAccess()will
return GSM_READY. Use this as a flag to
set the notConnected variable
to true or false. Once connected, the
remainder of setup will run.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]

Finish setup with some information to the


serial monitor.
Serial.println("GSM initialized.");
Serial.println("Waiting for messages");
}
[Get Code]

SMS messages are received by the


modem. SIM cards have some memory
space to store incoming SMS. The
number of SMS the card can hold can
be as few as 10, or as many as 200,
depending on the SIM. You should
check with your provider to determine
how many your SIM can keep in
memory.
In loop(), create a variable of type char to
temporarily hold characters from any
SMS received. Use sms.available() to
check for the presence of any
messages on the SIM :
void loop()
{

char c;
if (sms.available())
{
[Get Code]

If a SMS is available, retrieve the


remote sender's number by
calling sms.remoteNumber(remoteNumber, 20).
theremoteNumber argument is
the char array you declared in the
beginning of the sketch, it can be no
longer than 20 characters. Send this
number to the serial monitor.
Serial.println("Message received from:");
sms.remoteNumber(remoteNumber, 20);
Serial.println(remoteNumber);
[Get Code]

It's possible to delete SMS messages


by calling sms.flush(). Using sms.peek() it's
possible to identify the message index
number, which could be helpful for
removal
The code below won't remove any from
the SIM, but you could iterate through
a for loop, or identify a specific index
number to remove, instead of the
dummy # used below
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}
[Get Code]

To read a message, use sms.read().


Here, you'll store each character from
the message into the variable c and
print it out as it gets read.
while(c=sms.read())
Serial.print(c);
[Get Code]

Indicate the message is complete and


remove it from memory with sms.flush().
Serial.println("\nEND OF MESSAGE");
sms.flush();
Serial.println("MESSAGE DELETED");
}
[Get Code]

Add a brief delay and close the loop.


delay(1000);
}
[Get Code]

Once your code is uploaded, open the


serial monitor. With a phone, or other
SMS enabled service, send a SMS to
the number of your SIM. You should

void loop()
{
char c;

see the message print out on screen


when it is received.
/*
SMS receiver

// If there are any SMSs available()


if (sms.available())
{
Serial.println("Message received from:");

This sketch, for the Arduino GSM shield, waits


for SMS messages
and displays them through the Serial port.

// Get remote number


sms.remoteNumber(remoteNumber, 20);
Serial.println(remoteNumber);

Circuit:
* GSM shield
created 25 Feb 2012
by Javier Zorzano / TD

// This is just an example of message


disposal
// Messages starting with # should be
discarded
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}

This example is in the public domain.


*/
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""

// Read message bytes and print them


while(c=sms.read())
Serial.print(c);

// initialize the library instance


GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSM_SMS sms;

Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");

char remoteNumber[20]; // Holds the emitting


number
}

void setup()
{
// initialize serial communications
Serial.begin(9600);

delay(1000);
}

Serial.println("SMS Messages Receiver");


// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}

GSM Web Client


This sketch connects an Arduino to the
Arduino homepage, http://arduino.cc,
through a GSM shield. It then prints the
content of the page through the serial
monitor.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card with a data connection
Circuit

#define GPRS_APN
"GPRS_APN"
#define GPRS_LOGIN "login"
#define GPRS_PASSWORD "password"
[Get Code]

Initialize instances of the classes you're


going to use. You're going to need the
GSM, GPRS, and GSMClient classes.
GSMClient client;
GPRS gprs;
GSM gsmAccess;
[Get Code]

Create some variables to hold the


server, path, and port you wish to
connect to.
char server[] = "arduino.cc";
char path[] = "/";
int port = 80;
[Get Code]

In setup, open a serial connection to the


computer. After opening the
connection, send a message indicating
the sketch has started.
void setup(){
Serial.begin(9600);
Serial.println("Starting Arduino web client.");
[Get Code]

Create a local variable to track the


connection status. You'll use this to
keep the sketch from starting until the
SIM is connected to the network :
boolean notConnected = true;
[Get Code]

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

SIM cards may have a PIN number that


enables their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Define a number of constants that


contain information about the GPRS
network you're going to connect to.
You'll need the Access Point Name
(APN), login, and password. To obtain
this information, contact your network
provider for the most up to date
information. This page has some
information about various carrier
settings, but it may not be current.

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. You'll also
connect to the GPRS network
using gprs.attachGPRS(). This requires the
APN, login, and password you declared
earlier. By placing this inside
a while() loop, you can continually check
the status of the connection and wait
for them to both become true before
proceeding.
When the modem does connect and
has attached itself to the GPRS
network, gsmAccess() will
return GSM_READY. Use this as a flag to
set the notConnected variable to true or false.
Once connected, the remainder
of setup will run.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)

(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]

Attempt to connect to the server


using client.connect(). connect() requires two
arguments, the server and port. Once
connected to the server, make a HTTP
request by calling client.print(). A typical
web request looks like "GET pathname
HTTP/1.0". print will send the message,
just as a browser would.
if (client.connect(server, port))
{
Serial.println("connected");
client.print("GET ");
client.print(path);
client.println(" HTTP/1.0");
client.println();
}

}
}
[Get Code]

Once your code is uploaded, open the


serial monitor. You should see the
HTML of http://arduino.cc print out on
screen when it is received.
/*
GSM Web client
This sketch connects to a website using a GSM
shield.
Circuit:
* GSM shield attached
created 8 Mar 2012
by Tom Igoe
*/
// libraries
#include <GSM.h>

[Get Code]

If the connection to the server failed,


make a note of it in the serial monitor,
and close up setup.
else
{
Serial.println("connection failed");
}
}
[Get Code]

Inside loop, check to see if there are


bytes returned from the server. If so,
read them and print them to the serial
monitor.
if (client.available())
{
char c = client.read();
Serial.print(c);
}
[Get Code]

If the server disconnects, which it will


typically do once it has completed the
HTTP request, stop the client locally
and close the loop.
if (!client.available() && !client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:

for(;;)
;

// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" // replace
your GPRS APN
#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess; // include a 'true' parameter
for debug enabled
// This example downloads the URL
"http://arduino.cc/"
// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/";
int port = 80; // 80 for HTTP
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Starting Arduino web client.");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes

while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port))
{
Serial.println("connected");
// Make a HTTP request:
client.print("GET ");
client.print(path);
client.println(" HTTP/1.0");
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.available() && !client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
for(;;)
;
}
}

GSM Web Server


This sketch turns the Arduino with a
GSM shield and a data enabled SIM
card into a web server. When the

Arduino receives a request from a


connected client, it sends back the
value of analog inputs 0-5.
Not all network operators allow
incoming data requests from outside
their network. This means you can
create a web server with the GSM
shield, but you may not be able to
connect to it from the public internet;
only from another data enabled device
from the same provider on the same
network. You should check with your
provider to see what specific policies
they have in place regarding incoming
data connections.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card with a data connection
(optional) 6 potentiometers or other
analog inputs attached to A0-A5
Circuit

#define GPRS_APN
"GPRS_APN"
#define GPRS_LOGIN "login"
#define GPRS_PASSWORD "password"
[Get Code]

Initialize instances of the classes you're


going to use. You're going to need the
GSM, GPRS, and GSMServer classes.
When you instantiate
the GSMServer class, you'll need to tell
it which port to listen for incoming
connections. Port 80 is the default port
for HTTP requests.
GPRS gprs;
GSM gsmAccess;
GSMServer server(80);
[Get Code]

In setup, open a serial connection to the


computer. After opening the
connection, send a message indicating
the sketch has started.
void setup(){
Serial.begin(9600);
Serial.println("Starting Arduino web client.");
[Get Code]

Create a local variable to track the


connection status. You'll use this to
keep the sketch from starting until the
SIM is connected to the network :
boolean notConnected = true;
[Get Code]

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

SIM cards may have a PIN number that


enables their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Define a number of constants that


contain information about the GPRS
network you're going to connect to.
You'll need the Access Point Name
(APN), login, and password. To obtain
this information, contact your network
provider for the most up to date
information. This page has some
information about various carrier
settings, but it may not be current.

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. You'll also
connect to the GPRS network
using gprs.attachGPRS(). This requires the
APN, login, and password you declared
earlier. By placing this inside
a while() loop, you can continually check
the status of the connection and wait
for them to both become true before
proceeding.
When the modem does connect and
has attached itself to the GPRS
network, gsmAccess() will
return GSM_READY. Use this as a flag to
set the notConnected variable
to true or false. Once connected, the
remainder of setup will run.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))

notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}

Read through the analog inputs and


send the values to the client.

}
[Get Code]

Start the server using server.begin(). You


can request the server's IP address
with grps.getIPAddress() and end the setup.
server.begin();
IPAddress LocalIP = gprs.getIPAddress();
Serial.println("Server IP address=");
Serial.println(LocalIP);
}
[Get Code]

In loop, create an instance


of GSMClient and check if there are any
active connections
void loop() {
GSMClient client = server.available();

for (int analogChannel = 0; analogChannel < 6;


analogChannel++) {
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(analogRead(analogChannel))
;
client.println("<br />");
}
[Get Code]

Send a closing tag for the webpage,


and stop the client connection before
closing the loop.
client.println("</html>");
//necessary delay
delay(1000);
client.stop();
}
}
}
}
}
[Get Code]

if (client)
{
[Get Code]

While the client is connected, and there


is data waiting to be read, begin to read
the request. Read through the available
bytes until a newline character has
been received.
In this instance, you won't actually do
anything with the request, it's assumed
that it is a HTTP request, and you'll
serve up a web page.
while (client.connected())
{
if (client.available())
{
Serial.println("Receiving request!");
bool sendResponse = false;
while(char c=client.read()) {
if (c == '\n') sendResponse = true;
}
[Get Code]

Once your code is uploaded, open the


serial monitor. Once the IP address is
printed to the serial monitor, enter it
into a web browser. You should see a
webpage that reports the analog input
values on each the Arduino's six inputs.
if you cannot connect to the IP address,
make sure your network operator
enables incoming traffic.
/*
GSM Web Server
A simple web server that shows the value of the
analog input pins.
using a GSM shield.
Circuit:
* GSM shield attached
* Analog inputs attached to pins A0 through A5
(optional)

Once the request has been read, start


to send a standard HTTP response
header with client.print() andclient.println().

created 8 Mar 2012


by Tom Igoe
*/

if (sendResponse)
{
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
[Get Code]

// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN

"GPRS_APN" // replace

your GPRS APN


#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GPRS gprs;
GSM gsmAccess; // include a 'true' parameter
for debug enabled
GSMServer server(80); // port 80 (http default)
// timeout
const unsigned long __TIMEOUT__ = 10*1000;
void setup()
{
// initialize serial communications
Serial.begin(9600);
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}

{
while (client.connected())
{
if (client.available())
{
Serial.println("Receiving request!");
bool sendResponse = false;
while(char c=client.read()) {
if (c == '\n') sendResponse = true;
}
// if you've gotten to the end of the line
(received a newline
// character)
if (sendResponse)
{
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
// output the value of each analog input
pin
for (int analogChannel = 0; analogChanne
l < 6; analogChannel++) {
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(analogRead(analogChannel))
;
client.println("<br />");
}
client.println("</html>");
//necessary delay
delay(1000);
client.stop();
}
}
}
}
}

Serial.println("Connected to GPRS network");


// start server
server.begin();
//Get IP.
IPAddress LocalIP = gprs.getIPAddress();
Serial.println("Server IP address=");
Serial.println(LocalIP);
}
void loop() {
// listen for incoming clients
GSM3MobileClientService
client = server.available();

if (client)

GSM Xively Client


This example shows you how to
answer a HTTP request using a GSM
shield attached to an Arduino.
Specifically, it connects to xively.com, a
free datalogging site. The example
requires that you set up a xively.com
account, as well as a xively feed (for
more information on setting up an input
feed, please click here). Your GSM
shield will then connect to that feed and
upload sensor data.
To use a data connection with the GSM
shield, you'll need your provider's
Access Point Name (APN), login, and

password. To obtain this information,


contact the network provider for the
most up to date information. This
page has some information about
various carrier settings, but it may not
be current.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card with a data connection
Analog sensor attached to A0
Software Required
xively.com account
xively.com feed that accepts two data
items
Circuit

Declare the various settings for your


Xively account; your API key, feed ID,
and project name (the user agent).
#define APIKEY
"YOUR API KEY GOES
HERE"
#define FEEDID
00000
#define USERAGENT
"My Project"
[Get Code]

SIM cards may have a PIN number that


enables their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Define a number of constants that


contain information about the GPRS
network you're going to connect to.
You'll need the Access Point Name
(APN), login, and password. To obtain
this information, contact your network
provider for the most up to date
information. This page has some
information about various carrier
settings, but it may not be current.
#define GPRS_APN
"GPRS_APN"
#define GPRS_LOGIN "login"
#define GPRS_PASSWORD "password"
[Get Code]

Initialize instances of the classes you're


going to use. You're going to need the
GSM, GPRS, GSMServer,
and GSMClientclasses.
GSMClient client;
GPRS gprs;
GSM gsmAccess;
[Get Code]

Create some variables to store


information you're going to need in the
sketch; a char array to hold the URL,
and some variables for setting timing
intervals.
char server[] = "api.xively.com";
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
const unsigned long postingInterval = 10*1000;
[Get Code]

In setup, open a serial connection to the


computer.
void setup(){
Serial.begin(9600);
[Get Code]

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

Create a local variable to track the


connection status. You'll use this to

keep the sketch from starting until the


SIM is connected to the network :
boolean notConnected = true;
[Get Code]

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. You'll also
connect to the GPRS network
using gprs.attachGPRS(). This requires the
APN, login, and password you declared
earlier. By placing this inside
a while() loop, you can continually check
the status of the connection and wait
for them to both become true before
proceeding.
When the modem does connect and
has attached itself to the GPRS
network, gsmAccess() will
return GSM_READY. Use this as a flag to
set the notConnected variable to true or false.
Once connected, you can close setup.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
}
[Get Code]

You're going to use some custom


functions in this sketch. The first will
make a HTTP connection to the server
and send any data. Declare a function
named sendData() that accepts an
argument of type int
void sendData(int thisData)
{
[Get Code]

Check to see if there is a successful


connection to the server
if (client.connect(server, 80))
{
Serial.println("connecting...");
[Get Code]

When connected, send a HTTP PUT


request with the information about your
feed

client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.print("Host: api.xively.com\n");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
[Get Code]

You'll need to calculate the length of


the data you're sending. The length will
be 8 bytes for the term "sensor1," plus
the number of digits of the data. You'll
create a new function
named getLength() in a moment to handle
this information. Once calculated, send
the length to the server, and the last
pieces of the PUT.
Last, send the data to the server.
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
client.print("Content-Type: text/csv\n");
client.println("Connection: close");
client.println();
client.print("sensor1,");
client.println(thisData);
}
[Get Code]

If the connection attempt was not


successful, send a status message to
the serial monitor, and disconnect from
the server.
else
{
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
[Get Code]

Update the time that the last


connection, or attempt, happened
before closing the function.
lastConnectionTime = millis();
}
[Get Code]

Create another function,


named getLength(), for determining the
length of the data being sent in bytes.
int getLength(int someValue)
{
[Get Code]

Create a variable named digits to hold


the number of bytes. You know that

there will always be at least one digit


being sent.
To find the total number of digits to
send, continually divide the value by
ten, adding one to the digit count each
time you divide, until you reach 0.
int digits = 1;
int dividend = someValue /10;
while (dividend > 0)
{
dividend = dividend /10;
digits++;
}

lastConnected = client.connected();
}
[Get Code]

Once your code is uploaded, open the


serial monitor for debugging, and check
your xively.com feed to see updates.
/*
GSM Xively client
This sketch connects an analog sensor to
Xively (http://www.xively.com)
using a Telefonica GSM/GPRS shield.

[Get Code]

Return the number of digits and close


the function.
return digits;
}
[Get Code]

Inside loop, read the value from the


analog sensor and store it in a local
variable
void loop(){
int sensorReading = analogRead(A0);
[Get Code]

If there are bytes available, read them


and send them to the serial port.
if (client.available())
{
char c = client.read();
Serial.print(c);
}

This example has been updated to use version


2.0 of the Xively.com API.
To make it work, create a feed with a
datastream, and give it the ID
sensor1. Or change the code below to match
your feed.
Circuit:
* Analog sensor attached to analog in 0
* GSM shield attached to an Arduino
* SIM card with a data plan
created 4 March 2012
by Tom Igoe
and adapted for GSM shield by David Del Peral
This code is in the public domain.
http://arduino.cc/en/Tutorial/GSMExamplesXivel
yClient
*/

[Get Code]

Check for an active network


connection. If there isn't one, but there
was one last time through loop(), then
stop the client:
if (!client.connected() && lastConnected)
{
client.stop();
}
[Get Code]

If there is no connection, and ten


seconds have passed since the last
connection, or connection attempt, then
connect again and send data
if(!client.connected() && ((millis() lastConnectionTime) > postingInterval))
{
sendData(sensorReading);
}
[Get Code]

Store the state of the connection for


next time through loop() and close it up.

// libraries
#include <GSM.h>
// Xively Client data
#define APIKEY
"YOUR API KEY GOES
HERE" // replace your xively api key here
#define FEEDID
00000
//
replace your feed ID
#define USERAGENT
"My Project"
//
user agent is the project name
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" //
replace your GPRS APN
#define GPRS_LOGIN "login" // replace
with your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance:
GSMClient client;
GPRS gprs;

GSM gsmAccess;
// 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(216,52,233,121); //
numeric IP for api.xively.com
char server[] = "api.xively.com";
// name
address for xively API
unsigned long lastConnectionTime = 0;
//
last time you connected to the server, in
milliseconds
boolean lastConnected = false;
//
state of the connection last time through the
main loop
const unsigned long postingInterval = 10*1000;
//delay between updates to Xively.com
void setup()
{
// initialize serial communications and wait for
port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with
the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
}
void loop()
{
// read the analog sensor:
int sensorReading = analogRead(A0);
// if there's incoming data from the net
connection.
// send it out the serial port. This is for
debugging
// purposes only:
if (client.available())

{
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was
one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected)
{
client.stop();
}
// if you're not connected, and ten seconds
have passed since
// your last connection, then connect again and
send data:
if(!client.connected() && ((millis() lastConnectionTime) > postingInterval))
{
sendData(sensorReading);
}
// store the state of the connection for next time
through
// the loop:
lastConnected = client.connected();
}
/*
This method makes a HTTP connection to the
server.
*/
void sendData(int thisData)
{
// if there's a successful connection:
if (client.connect(server, 80))
{
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in
bytes:
// 8 bytes for "sensor1," + number of digits of
the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();

// here's the actual content of the PUT


request:
client.print("sensor1,");
client.println(thisData);
}
else
{
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made
or attempted
lastConnectionTime = millis();
}
/*
This method calculates the number of digits in
the
sensor reading. Since each digit of the ASCII
decimal
representation is a byte, the number of digits
equals
the number of bytes.
*/
int getLength(int someValue)
{
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0)
{
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}

GSM Xively Client String


This example shows you how to
answer a HTTP request using a GSM
shield attached to an Arduino.
Specifically, it connects to xively.com, a
free datalogging site and sends data as
a string. The example requires that you
set up a xively.com account, as well as
a xively feed (for more information on
setting up an input feed, please click
here). Your GSM shield will then

connect to that feed and upload sensor


data.
To use a data connection with the GSM
shield, you'll need your provider's
Access Point Name (APN), login, and
password. To obtain this information,
contact the network provider for the
most up to date information. This
page has some information about
various carrier settings, but it may not
be current.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card with a data connection
Analog sensors attached to A0 and A1
Software Required
xively.com account
xively.com feed that accepts two data
items
Circuit

this information, contact your network


provider for the most up to date
information. This page has some
information about various carrier
settings, but it may not be current.
#define GPRS_APN
"GPRS_APN"
#define GPRS_LOGIN "login"
#define GPRS_PASSWORD "password"
[Get Code]

Initialize instances of the classes you're


going to use. You're going to need the
GSM, GPRS, GSMServer,
and GSMClientclasses.
GSMClient client;
GPRS gprs;
GSM gsmAccess;
[Get Code]

Create some variables to store


information you're going to need in the
sketch; a char array to hold the URL,
and some variables for setting timing
intervals.
char server[] = "api.xively.com";
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
const unsigned long postingInterval = 10*1000;
[Get Code]

In setup, open a serial connection to the


computer.
void setup(){
Serial.begin(9600);
[Get Code]

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

Declare the various settings for your


xively account; your API key, feed ID,
and project name (the user agent).
#define APIKEY
"YOUR API KEY GOES
HERE"
#define FEEDID
00000
#define USERAGENT
"My Project"
[Get Code]

SIM cards may have a PIN number that


enables their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Define a number of constants that


contain information about the GPRS
network you're going to connect to.
You'll need the Access Point Name
(APN), login, and password. To obtain

Create a local variable to track the


connection status. You'll use this to
keep the sketch from starting until the
SIM is connected to the network :
boolean notConnected = true;
[Get Code]

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. You'll also
connect to the GPRS network
using gprs.attachGPRS(). This requires the
APN, login, and password you declared
earlier. By placing this inside
a while() loop, you can continually check
the status of the connection and wait
for them to both become true before
proceeding.
When the modem does connect and
has attached itself to the GPRS
network, gsmAccess() will
return GSM_READY. Use this as a flag to

set the notConnected variable to true or false.


Once connected, sned a status
message to the serial monitor and
close setup.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("Connected to GPRS network");
}
[Get Code]

You're going to use a custom function


to make the HTTP connection to the
server and send any data. Declare a
function named sendData() that accepts a
String as an argument.
void sendData(String thisData)
{
[Get Code]

Check to see if there is a successful


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

client.println(thisData);
}
[Get Code]

If the connection attempt was not


successful, send a status message to
the serial monitor, and disconnect from
the server.
else
{
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
[Get Code]

Update the time that the last


connection, or attempt, happened
before closing the function.
lastConnectionTime = millis();
}
[Get Code]

Inside loop, read the value from A0 and


store it in a local variable
void loop(){
int sensorReading = analogRead(A0);
[Get Code]

Convert the data to a string and prefix it


with "sensor1, "
String dataString = "sensor1,";
dataString += sensorReading;
[Get Code]

[Get Code]

When connected, send a HTTP PUT


request with the information about your
feed. length() will return the length of the
data you're sending.
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.print("Host: api.xively.com\n");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(thisData.length());
[Get Code]

Once the length has been sent, pass


on the last pieces of the PUT request,
and the data to the server.
client.print("Content-Type: text/csv\n");
client.println("Connection: close\n");
client.println();

If your xively feed is set up to handle


multiple values, you can append
multiple readings to the the String.
Read the value on A1 and add it to the
String as "sensor2".
int otherSensorReading = analogRead(A1);
dataString += "\nsensor2,";
dataString += otherSensorReading;
[Get Code]

If there are bytes available, read them


and send them to the serial port.
if (client.available())
{
char c = client.read();
Serial.print(c);
}
[Get Code]

Check for an active network


connection. If there isn't one, but there
was one last time through loop(), then
stop the client:
if (!client.connected() && lastConnected)
{
client.stop();
}
[Get Code]

If there is no connection, and ten


seconds have passed since the last
connection, or connection attempt, then
connect again and send data
if(!client.connected() && ((millis() lastConnectionTime) > postingInterval))
{
sendData(sensorReading);
}
[Get Code]

Store the state of the connection for


next time through loop() and close it up.
lastConnected = client.connected();
}
[Get Code]

Once your code is uploaded, open the


serial monitor for debugging, and check
your xively.com feed to see updates.
/*
Xively client with Strings
This sketch connects two analog sensors to
Xively (http://www.xively.com)
through a Telefonica GSM/GPRS shield.
This example has been updated to use version
2.0 of the Xively.com API.
To make it work, create a feed with two
datastreams, and give them the IDs
sensor1 and sensor2. Or change the code
below to match your feed.
This example uses the String library, which is
part of the Arduino core from
version 0019.
Circuit:
* Analog sensors attached to A0 and A1
* GSM shield attached to an Arduino
* SIM card with a data plan
created 8 March 2012
by Tom Igoe
and adapted for GSM shield by David Del Peral
This code is in the public domain.
*/
// Include the GSM library
#include <GSM.h>
// Xively login information
#define APIKEY
"YOUR API KEY GOES
HERE" // replace your xively api key here
#define FEEDID
00000
//
replace your feed ID
#define USERAGENT
"My Project"
//
user agent is the project name

// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" // replace
your GPRS APN
#define GPRS_LOGIN "login" // replace with
your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;
// 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(216,52,233,121); //
numeric IP for api.xively.com
char server[] = "api.xively.com";
// name
address for Xively API
unsigned long lastConnectionTime = 0;
//
last time you connected to the server, in
milliseconds
boolean lastConnected = false;
//
state of the connection last time through the
main loop
const unsigned long postingInterval = 10*1000;
// delay between updates to Xively.com
void setup()
{
// initialize serial communications and wait for
port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with
the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_R
EADY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}

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

Serial.println("Connected to GPRS network");


}

// send the HTTP PUT request:


client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(thisData.length());

void loop()
{
// read the sensor on A0
int sensorReading = analogRead(A0);
// convert the data to a String
String dataString = "sensor1,";
dataString += sensorReading;
// you can append multiple readings to this
String to
// send the xively feed multiple values
int otherSensorReading = analogRead(A1);
dataString += "\nsensor2,";
dataString += otherSensorReading;

// last pieces of the HTTP PUT request


client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();

// if there's incoming data from the net


connection.
// send it out the serial port. This is for
debugging
// purposes only
if (client.available())
{
char c = client.read();
Serial.print(c);
}

// here's the actual content of the PUT request


client.println(thisData);
}
else
{
// if you couldn't make a connection
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made
or attempted:
lastConnectionTime = millis();
}

// if there's no net connection, but there was


one last time
// through the loop, then stop the client
if (!client.connected() && lastConnected)
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds
have passed since
// your last connection, then connect again and
send data
if(!client.connected() && (millis() lastConnectionTime > postingInterval))
{
sendData(dataString);
}
// store the state of the connection for next time
through
// the loop
lastConnected = client.connected();
}
// this method makes a HTTP connection to the
server
void sendData(String thisData)
{
// if there's a successful connection:

GSM Test Modem


This sketch tests the modem on the
GSM shield to see if it is working
correctly. You do not need a SIM card
for this example.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
Circuit

if(modem.begin())
Serial.println("modem.begin() succeeded");
else
Serial.println("ERROR, no modem answer.");
}
[Get Code]

Inside loop, use modem.getIMEI() to return


the IMEI number of the modem. This
number is unique to your GSM shield.
void loop()
{
// get modem IMEI
Serial.print("Checking IMEI...");
IMEI = modem.getIMEI();
[Get Code]

If there is a valid response from getIMEI(),


print it to the serial monitor and reset
the modem with modem.begin().
if(IMEI != NULL)
{
// show IMEI in serial monitor
Serial.println("Modem's IMEI: " + IMEI);
// reset modem to check booting:
Serial.print("Reseting modem...");
modem.begin();
[Get Code]

Once reset, check the IMEI again. If it


is a valid return again, the modem is
functioning as expected.

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

Create an instance of
the GSMModem class:
GSMModem modem;

Create a variable to hold the IMEI


number of the modem
String IMEI = "";
[Get Code]

In setup, open a serial connection to the


computer. After opening the
connection, send a message indicating
the sketch has started.
void setup(){
Serial.begin(9600);
Serial.print("Starting modem test...");
[Get Code]

Call modem.begin() to start the modem.


Send a status message depending on
the outcome, and end setup().

if(modem.getIMEI() != NULL)
{
Serial.println("Modem is functoning
properly");
}
[Get Code]

If, after resetting the modem, there is


not a valid return from getIMEI(), report
an error
else
{
Serial.println("Error: getIMEI() failed after
modem.begin()");
}
[Get Code]

If you never received an IMEI after


starting the sketch, report it, and end
the program.
}
else
{
Serial.println("Error: Could not get IMEI");
}
// do nothing:
while(true);
}
[Get Code]

Once your code is uploaded, open the


serial monitor. You should see the

Serial.println("Error: getIMEI() failed after


modem.begin()");
}
}
else
{
Serial.println("Error: Could not get IMEI");
}
// do nothing:
while(true);
}

HTML of http://arduino.cc print out on


screen when it is received.
/*
This example test if your modem is working
correctly.
Circuit:
* GSM shield attached (using digital pins 2, 3,
and 7)
Created 12 Jun 2012
by David del Peral
modified 21 Nov 2012
by Tom Igoe
*/
// libraries
#include <GSM.h>
// modem verification object
GSMModem modem;
// IMEI variable
String IMEI = "";
void setup()
{
// initialize serial communications
Serial.begin(9600);
// start modem test (reset and check response)
Serial.print("Starting modem test...");
if(modem.begin())
Serial.println("modem.begin() succeeded");
else
Serial.println("ERROR, no modem answer.");
}
void loop()
{
// get modem IMEI
Serial.print("Checking IMEI...");
IMEI = modem.getIMEI();
// check IMEI response
if(IMEI != NULL)
{
// show IMEI in serial monitor
Serial.println("Modem's IMEI: " + IMEI);
// reset modem to check booting:
Serial.print("Reseting modem...");
modem.begin();
// get and check IMEI one more time
if(modem.getIMEI() != NULL)
{
Serial.println("Modem is functoning
properly");
}
else
{

GSM Test GPRS


This sketch tests the GPRS data
connection on the GSM shield. It tries
to connect to arduino.cc.
To use a data connection with the GSM
shield, you'll need your provider's
Access Point Name (APN), login, and
password. To obtain this information,
contact the network provider for the
most up to date information. This
page has some information about
various carrier settings, but it may not
be current.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card with data connection
Circuit

Create some variables to hold the


server, path, and proxy you wish to
connect to.
char url[] = "arduino.cc";
char path[] = "/";
char urlproxy[] = "http://arduino.cc";
[Get Code]

Create a variable to hold a response


from the server, and a flag to indicate f
you wil be using a proxy or not.
String response = "";
boolean use_proxy = false;
[Get Code]

In setup, open a serial connection to the


computer.
void setup(){
Serial.begin(9600);
}
[Get Code]

You're going to create a custom


function to handle serial input from the
serial monitor. make a named function
that accepts a char array as an
argument.
int readSerial(char result[])
{
[Get Code]

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

SIM cards may have a PIN number that


enables their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Initialize instances of the classes you're


going to use. You're going to need the
GSM, GPRS, and GSMClient classes.
GSMClient client;
GPRS gprsAccess;
GSM gsmAccess;
[Get Code]

Create some status messages to send


to the serial monitor:
String oktext = "OK";
String errortext = "ERROR";

make a variable to act as a counter.


While there is serial information
available, read it into the char array. If a
newline character is encountered,
terminate the array and return to the
main program.
int i = 0;
while(1)
{
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar == '\n')
{
result[i] = '\0';
return 0;
}
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
}
}
}
[Get Code]

[Get Code]

In loop(), set the proxy flag to false

void loop()
{
use_proxy = false;

Serial.println(oktext);
[Get Code]
[Get Code]

Start the connection to the GSM


network by passing the PIN number (if
applicable) to gsmAccess.begin().
Serial.print("Connecting GSM network...");
if(gsmAccess.begin(PINNUMBER)!=GSM_RE
ADY)
{
Serial.println(errortext);
while(true);
}
Serial.println(oktext);
[Get Code]

Create a char array to hold the APN.


Use the readSerial() function you created
to get the bytes from the serial monitor
char apn[50];
Serial.print("Enter your APN: ");
readSerial(apn);
Serial.println(apn);
[Get Code]

Create a char array to hold the APN


login. Use the readSerial() function you
created to get the bytes from the serial
monitor
char login[50];
Serial.print("Now, enter your login: ");
readSerial(login);
Serial.println(login);
[Get Code]

Create a char array to hold the APN


password. Use the readSerial() function
you created to get the bytes from the
serial monitor
char password[20];
Serial.print("Finally, enter your password: ");
readSerial(password);
[Get Code]

Connect to the GPRS network


using gprs.attachGPRS(). This requires the
APN, login, and password you just
entered.
When the modem has attached itself to
the GPRS network, gsmAccess() will
return GSM_READY.
Serial.println("Attaching to GPRS with your
APN...");
if(gprsAccess.attachGPRS(apn, login, passwor
d)!=GPRS_READY)
{
Serial.println(errortext);
}
else{

Create a char array to hold any proxy


information you may need. Use
the readSerial() function you created to get
the bytes from the serial monitor.
char proxy[100];
Serial.print("If your carrier uses a proxy, enter
it, if not press enter: ");
readSerial(proxy);
Serial.println(proxy);
[Get Code]

If a proxy was indicated, ask for the


port number, and set the proxy flag
to true
int pport;
if(proxy[0] != '\0'){
// read proxy port introduced by user
char proxyport[10];
Serial.print("Enter the proxy port: ");
readSerial(proxyport);
// cast proxy port introduced to integer
pport = (int) proxyport;
use_proxy = true;
Serial.println(proxyport);
}
[Get Code]

Create a variable to indicate if you are


connected to the server or not.
With client.connect(), make a connection to
the server. How you make the
connection will depend on if you are
using a proxy or not.
Serial.print("Connecting and sending GET
request to arduino.cc...");
int res_connect;
if(use_proxy)
res_connect = client.connect(proxy, pport);
else
res_connect = client.connect(url, 80);
[Get Code]

if you have connected, make a HTTP


GET request using client.print().
if (res_connect)
{
client.print("GET ");
if(use_proxy)
client.print(urlproxy);
else
client.print(path);
client.println(" HTTP/1.0");
client.println();
Serial.println(oktext);
}

[Get Code]

If no connection was made, print out an


error
else
{
// if you didn't get a connection to the server
Serial.println(errortext);
}
[Get Code]

Check to see if the server returned any


bytes using client.available(). If there are,
read them into the responseString, then
cast them into a char array. Check the
array for the substring "200 OK", which
indicates a valid response from
arduino.cc.
Serial.print("Receiving response...");

Circuit:
* GSM shield attached
Created 18 Jun 2012
by David del Peral
*/
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess;
// GSM access: include a
'true' parameter for debug enabled
GPRS gprsAccess; // GPRS access
GSMClient client; // Client service for TCP
connection
// messages for serial monitor response
String oktext = "OK";
String errortext = "ERROR";

boolean test = true;


while(test)
{
if (client.available())
{
char c = client.read();
response += c;

// URL and path (for example: arduino.cc)


char url[] = "arduino.cc";
char urlproxy[] = "http://arduino.cc";
char path[] = "/";

char responsechar[response.length()+1];
response.toCharArray(responsechar, respo
nse.length()+1);
if(strstr(responsechar, "200 OK") != NULL){
Serial.println(oktext);
Serial.println("TEST COMPLETE!");
test = false;
}
}
[Get Code]

If the server has disconnected, stop the


client and close loop()
if (!client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
test = false;
}
}
}
}
[Get Code]

Once your code is uploaded, open the


serial monitor to see the status of the
connection.
/*
This test asks your APN data and try to connect
to arduino.cc site by GPRS.

// variable for save response obtained


String response = "";
// use a proxy
boolean use_proxy = false;
void setup()
{
// initialize serial communications
Serial.begin(9600);
}
void loop()
{
use_proxy = false;
// start GSM shield
// if your SIM has PIN, pass it as a parameter of
begin() in quotes
Serial.print("Connecting GSM network...");
if(gsmAccess.begin(PINNUMBER)!=GSM_RE
ADY)
{
Serial.println(errortext);
while(true);
}
Serial.println(oktext);
// read APN introduced by user
char apn[50];
Serial.print("Enter your APN: ");
readSerial(apn);
Serial.println(apn);

// Read APN login introduced by user


char login[50];
Serial.print("Now, enter your login: ");
readSerial(login);
Serial.println(login);

// if use a proxy, the path is arduino.cc URL


if(use_proxy)
client.print(urlproxy);
else
client.print(path);

// read APN password introduced by user


char password[20];
Serial.print("Finally, enter your password: ");
readSerial(password);

client.println(" HTTP/1.0");
client.println();
Serial.println(oktext);

// attach GPRS
Serial.println("Attaching to GPRS with your
APN...");
if(gprsAccess.attachGPRS(apn, login, passwor
d)!=GPRS_READY)
{
Serial.println(errortext);
}
else{
Serial.println(oktext);
// read proxy introduced by user
char proxy[100];
Serial.print("If your carrier uses a proxy, enter
it, if not press enter: ");
readSerial(proxy);
Serial.println(proxy);
// if user introduced a proxy, asks him for
proxy port
int pport;
if(proxy[0] != '\0'){
// read proxy port introduced by user
char proxyport[10];
Serial.print("Enter the proxy port: ");
readSerial(proxyport);
// cast proxy port introduced to integer
pport = (int) proxyport;
use_proxy = true;
Serial.println(proxyport);
}
// connection with arduino.cc and realize
HTTP request
Serial.print("Connecting and sending GET
request to arduino.cc...");
int res_connect;
// if use a proxy, connect with it
if(use_proxy)
res_connect = client.connect(proxy, pport);
else
res_connect = client.connect(url, 80);
if (res_connect)
{
// make a HTTP 1.0 GET request (client
sends the request)
client.print("GET ");

}
else
{
// if you didn't get a connection to the server
Serial.println(errortext);
}
Serial.print("Receiving response...");
boolean test = true;
while(test)
{
// if there are incoming bytes available
// from the server, read and check them
if (client.available())
{
char c = client.read();
response += c;
// cast response obtained from string to
char array
char responsechar[response.length()+1];
response.toCharArray(responsechar, respo
nse.length()+1);
// if response includes a "200 OK" substring
if(strstr(responsechar, "200 OK") != NULL){
Serial.println(oktext);
Serial.println("TEST COMPLETE!");
test = false;
}
}
// if the server's disconnected, stop the
client:
if (!client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
test = false;
}
}
}
}
/*
Read input serial
*/
int readSerial(char result[])
{
int i = 0;
while(1)

{
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar == '\n')
{
result[i] = '\0';
return 0;
}
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
}
}
}

GSM Scan Networks


This example prints out the IMEI
number of the modem, then checks to
see if it's connected to a carrier and
prints out its signal strength. It also
scans for all nearby networks.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card
Circuit

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

SIM cards may have a PIN number that


enables their functionality. Define the
PIN for your SIM. If your SIM has no
PIN, you can leave it blank :
#define PINNUMBER ""

Initialize instances of the classes you're


going to use. You're going to need the
GSM, GSMScanner,
and GSMModemclasses.
GSM gsmAccess;
GSMScanner scannerNetworks;
GSMModem modemTest;
[Get Code]

Create a variable to hold the IMEI


number, and a status messages to
send to the serial monitor:

String IMEI = "";

In loop(), scan and print out all available


networks. This may take some time

String errortext = "ERROR";


[Get Code]

In setup, open a serial connection to the


computer. After opening the
connection, send a message to the
Serial Monitor indicating the sketch has
started. Call
@scannerNetworks.begin()@@ to
reset the modem.
void setup(){
Serial.begin(9600);
Serial.println("GSM networks scanner");
scannerNetworks.begin();
[Get Code]

Create a local variable to track the


connection status. You'll use this to
keep the sketch from starting until the
SIM is connected to the network :
boolean notConnected = true;
[Get Code]

Connect to the network by


calling gsmAccess.begin(). It takes the SIM
card's PIN as an argument. By placing
this inside a while() loop, you can
continually check the status of the
connection. When the modem does
connect, gsmAccess()will
return GSM_READY. Use this as a flag to
set the notConnected variable
to true or false. Once connected, the
remainder of setup will run.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]

Get the IMEI of the modem


with modemTest.getIMEI() and print it out to
the serial monitor.
Serial.print("Modem IMEI: ");
IMEI = modemTest.getIMEI();
IMEI.replace("\n","");
if(IMEI != NULL)
Serial.println(IMEI);
[Get Code]

Serial.println("Scanning available networks. May


take some seconds.");
Serial.println(scannerNetworks.readNetworks()
);
[Get Code]

Print out the current connected carrier,


and the strength of the signal. Signal
strength is on a scale of 0-31, where 0
is the lowest, and 31 is the highest.
close the loop().
Serial.print("Current carrier: ");
Serial.println(scannerNetworks.getCurrentCarri
er());
Serial.print("Signal Strength: ");
Serial.print(scannerNetworks.getSignalStrengt
h());
Serial.println(" [0-31]");
[Get Code]

Once your code is uploaded, open the


serial monitor to see the status of the
connection.
/*
GSM Scan Networks
This example prints out the IMEI number of the
SIM card,
then check to see if it's connected to a carrier. If
so,
it prints the phone number associated with the
card.
Then it scans for nearby networks and prints
out their signal strengths.
Circuit:
* GSM shield attached
Created 8 Mar 2012
by Tom Igoe, implemented by Javier Carazo
Modified 18 Jan 2013
by Scott Fitzgerald
*/
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter
to enable debugging
GSMScanner scannerNetworks;
GSMModem modemTest;
// Save data variables

String IMEI = "";

);

// serial monitor result messages


String errortext = "ERROR";

// currently connected carrier


Serial.print("Current carrier: ");
Serial.println(scannerNetworks.getCurrentCarri
er());

void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("GSM networks scanner");
scannerNetworks.begin();

// returns strength and ber


// signal strength in 0-31 scale. 31 means
power > 51dBm
// BER is the Bit Error Rate. 0-7 scale. 99=not
detectable
Serial.print("Signal Strength: ");
Serial.print(scannerNetworks.getSignalStrengt
h());
Serial.println(" [0-31]");

// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter
of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
// get modem parameters
// IMEI, modem unique identifier
Serial.print("Modem IMEI: ");
IMEI = modemTest.getIMEI();
IMEI.replace("\n","");
if(IMEI != NULL)
Serial.println(IMEI);
// currently connected carrier
Serial.print("Current carrier: ");
Serial.println(scannerNetworks.getCurrentCarri
er());
// returns strength and ber
// signal strength in 0-31 scale. 31 means
power > 51dBm
// BER is the Bit Error Rate. 0-7 scale. 99=not
detectable
Serial.print("Signal Strength: ");
Serial.print(scannerNetworks.getSignalStrengt
h());
Serial.println(" [0-31]");
}
void loop()
{
// scan for existing networks, displays a list of
networks
Serial.println("Scanning available networks.
May take some seconds.");
Serial.println(scannerNetworks.readNetworks()

GSM PIN Management


This example helps you change or
remove the PIN of a SIM card with an
Arduino and GSM shield.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card
Circuit

connection, send a message to the


Serial Monitor indicating the sketch has
started. Call PINManager.begin() to reset the
modem.
void setup(){
Serial.begin(9600);
Serial.println("Change PIN example\n");
PINManager.begin();
[Get Code]

Check to see if the SIM is locked with a


PIN
while(!auth){
int pin_query = PINManager.isPIN();
if(pin_query == 1)
{
[Get Code]

If locked, ask for the PIN via the serial


monitor. You'll use a custom function
named readSerial() to parse the
information.
Serial.print("Enter PIN code: ");
user_input = readSerial();
[Get Code]

If the PIN is valid, set the auth flag


to true. Send a status message to the
serial monitor indicating the result. If
you enter the wrong PIN, you can try
again. After 3 missed attempts, the PIN
will be locked, and you'll need the PUK
number to unlock.

image of the Arduino GSM Shield on top of an


Arduino Uno

First, import the GSM library


#include <GSM.h>

Initialize an instance of
the GSMPin class.
GSMPIN PINManager;

Create your variables, starting with a


String to hold input from the serial
monitor. Also make a flag for checking f
the SIM has been authenticated with a
valid PIN, and messages for the serial
monitor.
String user_input = "";
boolean auth = false;
String oktext = "OK";
String errortext = "ERROR";
[Get Code]

In setup, open a serial connection to the


computer. After opening the

if(PINManager.checkPIN(user_input) == 0)
{
auth = true;
PINManager.setPINUsed(true);
Serial.println(oktext);
}
else
{
Serial.println("Incorrect PIN. Remember
that you have 3 opportunities.");
}
}
[Get Code]

If the SIM is in PUK lock mode, ask for


the PUK code and a new PIN
else if(pin_query == -1)
{
Serial.println("PIN locked. Enter PUK code:
");
String puk = readSerial();
Serial.print("Now, enter a new PIN code: ");
user_input = readSerial();
if(PINManager.checkPUK(puk, user_input) =
= 0)
{
auth = true;
PINManager.setPINUsed(true);

Serial.println(oktext);
}
else
{
Serial.println("Incorrect PUK or invalid new
PIN. Try again!.");
}
}
[Get Code]

If there is an error, and the PIN number


and PUK are both locked, send an
appropriate status message :
else if(pin_query == -2)
{
Serial.println("PIN & PUK locked. Use
PIN2/PUK2 in a mobile phone.");
while(true);
}
[Get Code]

String text = "";


while(1)
{
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar == '\n')
{
return text;
}
if(inChar!='\r')
text += inChar;
}
}
}
[Get Code]

acts as a PIN management tool,


allowing you to turn the PIN on or off,
and change it.
loop()

void loop()
{

If there's no PIN number, set


the auth flag to true
else
{
// SIM does not requires authetication
Serial.println("No pin necessary.");
auth = true;
}
}
[Get Code]

Check the registration on the GSM


network, and indicate if you're
connected or not, and if you're
roaming.
Serial.print("Checking register in GSM
network...");
if(PINManager.checkReg() == 0)
Serial.println(oktext);
else if(PINManager.checkReg() == 1)
Serial.println("ROAMING " + oktext);
else
{
Serial.println(errortext);
while(true);
}
}
[Get Code]

You're going to create a custom


function to handle serial input from the
serial monitor. Make a named function
of typeString.
String readSerial()
{
[Get Code]

While there is serial information


available, read it into a new String. If a
newline character is encountered,
return to the main program.

Serial.println("Choose an option:\n1 - On/Off


PIN.");
if(PINManager.getPINUsed())
Serial.println("2 - Change PIN.");
String user_op = readSerial();
if(user_op == "1")
{
Serial.println("Enter your PIN code:");
user_input = readSerial();
PINManager.switchPIN(user_input);
}
else if(user_op == "2" & PINManager.getPINUs
ed())
{
Serial.println("Enter your actual PIN code:");
String oldPIN = readSerial();
Serial.println("Now, enter your new PIN
code:");
String newPIN = readSerial();
PINManager.changePIN(oldPIN, newPIN);
}
else
{
Serial.println("Incorrect option. Try again!.");
}
delay(1000);
}
[Get Code]

Once your code is uploaded, open the


serial monitor to work with the PIN.
/*
This example helps you change your pin or
remove it.
Circuit:

* GSM shield attached


Created 12 Jun 2012
by David del Peral
*/
// libraries
#include <GSM.h>
// pin manager object
GSMPIN PINManager;
// save input in serial by user
String user_input = "";
// authenticated with PIN code
boolean auth = false;
// serial monitor result messages
String oktext = "OK";
String errortext = "ERROR";
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("Change PIN example\n");
PINManager.begin();
// check if the SIM have pin lock
while(!auth){
int pin_query = PINManager.isPIN();
if(pin_query == 1)
{
// if SIM is locked, enter PIN code
Serial.print("Enter PIN code: ");
user_input = readSerial();
// check PIN code
if(PINManager.checkPIN(user_input) == 0)
{
auth = true;
PINManager.setPINUsed(true);
Serial.println(oktext);
}
else
{
// if PIN code was incorrected
Serial.println("Incorrect PIN. Remember
that you have 3 opportunities.");
}
}
else if(pin_query == -1)
{
// PIN code is locked, user must enter PUK
code
Serial.println("PIN locked. Enter PUK code:
");
String puk = readSerial();
Serial.print("Now, enter a new PIN code: ");
user_input = readSerial();
// check PUK code

if(PINManager.checkPUK(puk, user_input) =
= 0)
{
auth = true;
PINManager.setPINUsed(true);
Serial.println(oktext);
}
else
{
// if PUK o the new PIN are incorrect
Serial.println("Incorrect PUK or invalid new
PIN. Try again!.");
}
}
else if(pin_query == -2)
{
// the worst case, PIN and PUK are locked
Serial.println("PIN & PUK locked. Use
PIN2/PUK2 in a mobile phone.");
while(true);
}
else
{
// SIM does not requires authetication
Serial.println("No pin necessary.");
auth = true;
}
}
// start GSM shield
Serial.print("Checking register in GSM
network...");
if(PINManager.checkReg() == 0)
Serial.println(oktext);
// if you are connect by roaming
else if(PINManager.checkReg() == 1)
Serial.println("ROAMING " + oktext);
else
{
// error connection
Serial.println(errortext);
while(true);
}
}
void loop()
{
// Function loop implements pin management
user menu
// Only if you SIM use pin lock, you can change
PIN code
// user_op variables save user option
Serial.println("Choose an option:\n1 - On/Off
PIN.");
if(PINManager.getPINUsed())
Serial.println("2 - Change PIN.");
String user_op = readSerial();
if(user_op == "1")
{
Serial.println("Enter your PIN code:");
user_input = readSerial();

// activate/deactivate PIN lock


PINManager.switchPIN(user_input);
}
else if(user_op == "2" & PINManager.getPINUs
ed())
{
Serial.println("Enter your actual PIN code:");
String oldPIN = readSerial();
Serial.println("Now, enter your new PIN
code:");
String newPIN = readSerial();
// change PIN
PINManager.changePIN(oldPIN, newPIN);
}
else
{
Serial.println("Incorrect option. Try again!.");
}
delay(1000);
}

Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card
Circuit

/*
Read input serial
*/
String readSerial()
{
String text = "";
while(1)
{
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar == '\n')
{
return text;
}
if(inChar!='\r')
text += inChar;
}
}
}

Band Management
This example shows how to use the
GSM Shield and Library to manage the
GSM band the modem connects to.
Check http://www.worldtimezone.com/g
sm.html for general GSM band
information. Typical regional
configurations are :
Europe, Africa, Middle East: EGSM(900)+DCS(1800)
USA, Canada, South America:
GSM(850)+PCS(1900)
Mexico: PCS(1900)
Brazil: GSM(850)+EGSM(900)+DCS(1800)+PCS(1900)

image of the Arduino GSM Shield on top of an


Arduino Uno
/*
Band Management
This sketch, for the Arduino GSM shield, checks
the band
currently configured in the modem and allows
you to change
it.
Please check
http://www.worldtimezone.com/gsm.html
Usual configurations:
Europe, Africa, Middle East: EGSM(900)+DCS(1800)
USA, Canada, South America:

GSM(850)+PCS(1900)
Mexico: PCS(1900)
Brazil: GSM(850)+EGSM(900)+DCS(1800)+PCS(1900)

if(operationSuccess)
{
while(true);
}
}

Circuit:
* GSM shield
created 12 June 2012
by Javier Zorzano, Scott Fitzgerald
This example is in the public domain.
*/
// libraries
#include <GSM.h>
// initialize the library instance
GSMBand band;
void setup()
{
// initialize serial communications
Serial.begin(9600);
// Beginning the band manager restarts the
modem
Serial.println("Restarting modem...");
band.begin();
Serial.println("Modem restarted.");
};
void loop()
{
// Get current band
String bandName = band.getBand(); // Get and
print band name
Serial.print("Current band:");
Serial.println(bandName);
Serial.println("Want to change the band youre
on?");
String newBandName;
newBandName = askUser();
// Tell the user what we are about to do
Serial.print("\nConfiguring band ");
Serial.println(newBandName);
// Change the band
boolean operationSuccess;
operationSuccess = band.setBand(newBandN
ame);
// Tell the user if the operation was OK
if(operationSuccess)
{
Serial.println("Success");
}
else
{
Serial.println("Error while changing band");
}

// This function offers the user different options


// through the Serial interface
// The user selects one
String askUser()
{
String newBand;
Serial.println("Select band:");
// Print the different options
Serial.println("1 : E-GSM(900)");
Serial.println("2 : DCS(1800)");
Serial.println("3 : PCS(1900)");
Serial.println("4 : E-GSM(900)+DCS(1800) ex:
Europe");
Serial.println("5 : GSM(850)+PCS(1900) Ex:
USA, South Am.");
Serial.println("6 : GSM(850)+EGSM(900)+DCS(1800)+PCS(1900)");
// Empty the incoming buffer
while(Serial.available())
Serial.read();
// Wait for an answer, just look at the first
character
while(!Serial.available());
char c= Serial.read();
if(c=='1')
newBand=GSM_MODE_EGSM;
else if(c=='2')
newBand=GSM_MODE_DCS;
else if(c=='3')
newBand=GSM_MODE_PCS;
else if(c=='4')
newBand=GSM_MODE_EGSM_DCS;
else if(c=='5')
newBand=GSM_MODE_GSM850_PCS;
else if(c=='6')
newBand=GSM_MODE_GSM850_EGSM_D
CS_PCS;
else
newBand=GSM_MODE_UNDEFINED;
return newBand;
}

GSM Test Web Server


This sketch creates a web server to
accept incoming connections on the
GSM shield. Some network providers
only allow requests from inside their
own network. You will need to check
with your network provider to make

sure your SIM card will accept


incoming HTTP requests.
Hardware Required
Arduino board
Arduino + Telefonica GSM/GPRS
Shield
SIM card with a data plan
Circuit

by David Cuartielles
modified 21 Nov 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/GSMToolsTest
WebServer
This example code is part of the public
domain
*/
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN
"GPRS_APN" //
replace your GPRS APN
#define GPRS_LOGIN "login" // replace
with your GPRS login
#define GPRS_PASSWORD "password" //
replace with your GPRS password
// initialize the library instance
GPRS gprs;
GSM gsmAccess; // include a 'true'
parameter for debug enabled
GSMServer server(80); // port 80 (http
default)
// timeout
const unsigned long __TIMEOUT__ = 10*10
00;
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("starting,..");
// connection state
boolean connected = true;

image of the Arduino GSM Shield on top of an


Arduino Uno

Code
/*
Basic Web Server
A simple web server that replies with
nothing, but prints the client's request
and the server IP address.
Circuit:
* GSM shield attached
created

// Start GSM shield


// If your SIM has PIN, pass it as a
parameter of begin() in quotes
while(!connected)
{
if((gsmAccess.begin(PINNUMBER)==GS
M_READY) &
(gprs.attachGPRS(GPRS_APN, GPRS
_LOGIN, GPRS_PASSWORD)==GPRS_RE
ADY))
connected = true;
else
{

Serial.println("Not connected");
delay(1000);
}
}
Serial.println("Connected to GPRS
network");

// start server
server.begin();
//Get IP.
IPAddress LocalIP = gprs.getIPAddress();
Serial.println("Server IP address=");
Serial.println(LocalIP);
}
void loop(){
GSMClient client = server.available();
if (client) {
if (client.available()) {
Serial.write(client.read());
}
}
}

LiquidCrystal Library

This library allows an Arduino board to


control LiquidCrystal displays (LCDs)
based on the Hitachi HD44780 (or a
compatible) chipset, which is found on
most text-based LCDs. The library
works with in either 4- or 8-bit mode
(i.e. using 4 or 8 data lines in addition
to the rs, enable, and, optionally, the rw
control lines).
Function
LiquidCrystal()
begin()
clear()
home()
setCursor()
write()
print()
cursor()
noCursor()
blink()
noBlink()

display()
noDisplay()
scrollDisplayLeft()
scrollDisplayRight()
autoscroll()
noAutoscroll()
leftToRight()
rightToLeft()
createChar()

LiquidCrystal()
Description
Creates a variable of
type LiquidCrystal. The display can be
controlled using 4 or 8 data lines. If the
former, omit the pin numbers for d0 to
d3 and leave those lines unconnected.
The RW pin can be tied to ground
instead of connected to a pin on the
Arduino; if so, omit it from this
function's parameters.
Syntax
LiquidCrystal(rs, enable, d4, d5, d6,
d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6,
d7)
LiquidCrystal(rs, enable, d0, d1, d2, d3,
d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2,
d3, d4, d5, d6, d7)
Parameters
rs: the number of the Arduino pin that is
connected to the RS pin on the LCD
rw: the number of the Arduino pin that
is connected to the RW pin on the LCD
(optional)
enable: the number of the Arduino pin
that is connected to the enable pin on
the LCD
d0, d1, d2, d3, d4, d5, d6, d7: the
numbers of the Arduino pins that are
connected to the corresponding data
pins on the LCD. d0, d1, d2, and d3 are
optional; if omitted, the LCD will be
controlled using only the four data lines
(d4, d5, d6, d7).
Example
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup()
{
lcd.begin(16,1);
lcd.print("hello, world!");
}
void loop() {}

begin()
Description
Initializes the interface to the LCD
screen, and specifies the dimensions
(width and height) of the
display. begin() needs to be called before
any other LCD library commands.
Syntax
lcd.begin(cols, rows)
Parameters
lcd: a variable of type LiquidCrystal
cols: the number of columns that the
display has
rows: the number of rows that the
display has

clear()
Description
Clears the LCD screen and positions
the cursor in the upper-left corner.
Syntax
lcd.clear()
Parameters
lcd: a variable of type LiquidCrystal

home()
Description
Positions the cursor in the upper-left of
the LCD. That is, use that location in
outputting subsequent text to the
display. To also clear the display, use
the clear() function instead.
Syntax
lcd.home()
Parameters
lcd: a variable of type LiquidCrystal

setCursor()
Description
Position the LCD cursor; that is, set the
location at which subsequent text
written to the LCD will be displayed.

Syntax
lcd.setCursor(col, row)
Parameters
lcd: a variable of type LiquidCrystal
col: the column at which to position the
cursor (with 0 being the first column)
row: the row at which to position the
cursor (with 0 being the first row)

write()
Description
Write a character to the LCD.
Syntax
lcd.write(data)
Parameters
lcd: a variable of type LiquidCrystal
data: the character to write to the
display
Returns
byte
write() will return the number of bytes
written, though reading that number is
optional
Example
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available()) {
lcd.write(Serial.read());
}
}

print()
Description
Prints text to the LCD.
Syntax
lcd.print(data)
lcd.print(data, BASE)
Parameters
lcd: a variable of type LiquidCrystal
data: the data to print (char, byte, int,
long, or string)
BASE (optional): the base in which to
print numbers: BIN for binary (base 2),
DEC for decimal (base 10), OCT for

octal (base 8), HEX for hexadecimal


(base 16).
Returns
byte
print() will return the number of bytes
written, though reading that number is
optional
Example

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup()
{
lcd.print("hello, world!");
}

void loop() {}

Before wiring the LCD screen to your


Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count
connector of the LCD screen, as you
can see in the image above.
To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screens VO pin (pin3).
click the images to enlarge

cursor()

Description
Display the LCD cursor: an underscore
(line) at the position to which the next
character will be written.
Syntax
lcd.cursor()
Parameters
lcd: a variable of type LiquidCrystal
Example
cursor() and noCursor()
LiquidCrystal - cursor() and noCursor()
The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch shows how to use
the cursor() and noCursor() methods to
control an underscore-style cursor.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.
This sketch prints "Hello World!" to the LCD and
uses the cursor() and noCursor() methods to
turn
on and off the cursor.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/LiquidCrystalCursor
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the
interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}

Code
/*
LiquidCrystal Library - Cursor
Demonstrates the use a 16x2 LCD display. The

void loop() {
// Turn off the cursor:
lcd.noCursor();
delay(500);
// Turn on the cursor:
lcd.cursor();
delay(500);
}

noCursor()
Description
Hides the LCD cursor.
Syntax
lcd.noCursor()
Parameters
lcd: a variable of type LiquidCrystal

blink()
Description
Display the blinking LCD cursor. If used
in combination with the cursor()
function, the result will depend on the
particular display.
Syntax
lcd.blink()
Parameters
lcd: a variable of type LiquidCrystal

header strip to the 14 (or 16) pin count


connector of the LCD screen, as you
can see in the image above.
To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screens VO pin (pin3).
click the images to enlarge

noBlink()
Description
Turns off the blinking LCD cursor.
Syntax
lcd.noBlink()
Parameters
lcd: a variable of type LiquidCrystal

LiquidCrystal - blink() and noBlink()


The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch shows how to use
the blink() and noBlink() methods to
blink a block-style cursor.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.
This sketch prints "Hello World!" to the LCD and
makes the
cursor block blink.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/LiquidCrystalBlink
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the
interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}

Code
/*
LiquidCrystal Library - Blink
Demonstrates the use a 16x2 LCD display. The

void loop() {
// Turn off the blinking cursor:
lcd.noBlink();
delay(3000);
// Turn on the blinking cursor:
lcd.blink();
delay(3000);
}

display()
Description
Turns on the LCD display, after it's
been turned off with noDisplay(). This
will restore the text (and cursor) that
was on the display.
Syntax
lcd.display()
Parameters
lcd: a variable of type LiquidCrystal

noDisplay()
Description
Turns off the LCD display, without
losing the text currently shown on it.
Syntax
lcd.noDisplay()
Parameters
lcd: a variable of type LiquidCrystal

LiquidCrystal - display() and


noDisplay()
The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch shows how to use
the display() and noDisplay() methods
to turn on and off the display. The text
to be displayed will still be preserved
when you use noDisplay() so it's a
quick way to blank the display without
losing everything on it.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count
connector of the LCD screen, as you

can see in the image above.


To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screen's VO pin (pin3).
click the images to enlarge

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

Demonstrates the use a 16x2 LCD display. The


LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.
This sketch prints "Hello World!" to the LCD and
uses the
display() and noDisplay() functions to turn on
and off
the display.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/LiquidCrystalDispla
y
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the
interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Code
/*
LiquidCrystal Library - display() and
noDisplay()

void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}
void loop() {
// Turn off the display:
lcd.noDisplay();
delay(500);
// Turn on the display:

lcd.display();
delay(500);
}

scrollDisplayLeft()
Description
Scrolls the contents of the display (text
and cursor) one space to the left.
Syntax
lcd.scrollDisplayLeft()
Parameters
lcd: a variable of type LiquidCrystal

scrollDisplayRight()
Description
Scrolls the contents of the display (text
and cursor) one space to the right.
Syntax
lcd.scrollDisplayRight()
Parameters
lcd: a variable of type LiquidCrystal

LiquidCrystal - scrollDisplayLeft() and


scrollDisplayRight()
The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch shows how to use
the scrollDisplayLeft() and scrollDisplayRight() m
ethods to reverse the direction the text
is flowing. It prints "Hello World!",
scrolls it offscreen to the left, then
offscreen to the right, then back to
home.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count

connector of the LCD screen, as you


can see in the image above.
To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screen's VO pin (pin3).
click the images to enlarge

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

Demonstrates the use a 16x2 LCD display. The


LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.
This sketch prints "Hello World!" to the LCD and
uses the
scrollDisplayLeft() and scrollDisplayRight()
methods to scroll
the text.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/LiquidCrystalScroll
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the
interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Code
/*
LiquidCrystal Library - scrollDisplayLeft() and
scrollDisplayRight()

void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
delay(1000);
}
void loop() {
// scroll 13 positions (string length) to the left
// to move it offscreen left:
for (int positionCounter = 0; positionCounter <
13; positionCounter++) {

// scroll one position left:


lcd.scrollDisplayLeft();
// wait a bit:
delay(150);
}
// scroll 29 positions (string length + display
length) to the right
// to move it offscreen right:
for (int positionCounter = 0; positionCounter <
29; positionCounter++) {
// scroll one position right:
lcd.scrollDisplayRight();
// wait a bit:
delay(150);
}
// scroll 16 positions (display length + string
length) to the left
// to move it back to center:
for (int positionCounter = 0; positionCounter <
16; positionCounter++) {
// scroll one position left:
lcd.scrollDisplayLeft();
// wait a bit:
delay(150);
}
// delay at the end of the full loop:
delay(1000);
}

autoscroll()
Description
Turns on automatic scrolling of the
LCD. This causes each character
output to the display to push previous
characters over by one space. If the
current text direction is left-to-right (the
default), the display scrolls to the left; if
the current direction is right-to-left, the
display scrolls to the right. This has the
effect of outputting each new character
to the same location on the LCD.
Syntax
lcd.autoscroll()
Parameters
lcd: a variable of type LiquidCrystal

noAutoscroll()
Description
Turns off automatic scrolling of the
LCD.
Syntax
lcd.noAutoscroll()

Parameters
lcd: a variable of type LiquidCrystal

leftToRight()
Description
Set the direction for text written to the
LCD to left-to-right, the default. This
means that subsequent characters
written to the display will go from left to
right, but does not affect previouslyoutput text.
Syntax
lcd.leftToRight()
Parameters
lcd: a variable of type LiquidCrystal

rightToLeft()
Description
Set the direction for text written to the
LCD to right-to-left (the default is left-toright). This means that subsequent
characters written to the display will go
from right to left, but does not affect
previously-output text.
Syntax
lcd.rightToLeft()
Parameters
lcd: a variable of type LiquidCrystal

createChar()
Description
Create a custom character (gylph) for
use on the LCD. Up to eight characters
of 5x8 pixels are supported (numbered
0 to 7). The appearance of each
custom character is specified by an
array of eight bytes, one for each row.
The five least significant bits of each
byte determine the pixels in that row.
To display a custom character on the
screen, write() its number.
NB : When referencing custom
character "0", if it is not in a variable,
you need to cast it as a byte, otherwise
the compiler throws an error. See the
example below.
Syntax
lcd.createChar(num, data)
Parameters
lcd: a variable of type LiquidCrystal

num: which character to create (0 to 7)


data: the character's pixel data
Example
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte smiley[8] = {
B00000,
B10001,
B00000,
B00000,
B10001,
B01110,
B00000,
};
void setup() {
lcd.createChar(0, smiley);
lcd.begin(16, 2);
lcd.write(byte(0));
}
void loop() {}

LiquidCrystal - "Hello World!"


The LiquidCrystal library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch prints "Hello
World!" to the LCD and shows the time
in seconds since the Arduino was
reset.

output of the sketch on a 2x16 LCD


The LCDs have a parallel interface,
meaning that the microcontroller has to

manipulate several interface pins at


once to control the display. The
interface consists of the following pins:
A register select (RS) pin that controls
where in the LCD's memory you're
writing data to. You can select either
the data register, which holds what
goes on the screen, or an instruction
register, which is where the LCD's
controller looks for instructions on what
to do next.
A Read/Write (R/W) pin that selects
reading mode or writing mode
An Enable pin that enables writing to
the registers
8 data pins (D0 -D7). The states of
these pins (high or low) are the bits that
you're writing to a register when you
write, or the values you're reading
when you read.
There's also a display constrast pin
(Vo), power supply pins (+5V and
Gnd) and LED Backlight (Bklt+
and BKlt-) pins that you can use to
power the LCD, control the display
contrast, and turn on and off the LED
backlight, respectively.
The process of controlling the display
involves putting the data that form the
image of what you want to display into
the data registers, then putting
instructions in the instruction register.
The LiquidCrystal Library simplifies this
for you so you don't need to know the
low-level instructions.
The Hitachi-compatible LCDs can be
controlled in two modes: 4-bit or 8-bit.
The 4-bit mode requires seven I/O pins
from the Arduino, while the 8-bit mode
requires 11 pins. For displaying text on
the screen, you can do most everything
in 4-bit mode, so example shows how
to control a 2x16 LCD in 4-bit mode.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer

breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count
connector of the LCD screen, as you
can see in the image above.
To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screens VO pin (pin3).

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

click the images to enlarge

Code
/*
LiquidCrystal Library - Hello World

Demonstrates the use a 16x2 LCD display. The


LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.
This sketch prints "Hello World!" to the LCD
and shows the time.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the


interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}

void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since
counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}

LiquidCrystal - Text Direction


(leftToRight() and rightToLeft()
The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch shows how to use
the leftToRight() and rightToLeft()
methods. These methods control which
way text flows from the cursor.
rightToLeft() causes text to flow to the left
from the cursor, as if the display is
right-justified.
leftToRight() causes text to flow to the right
from the cursor, as if the display is leftjustified.
This sketch prints a through l right to
left, then m through r left to right,
then s through z right to left again.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count
connector of the LCD screen, as you
can see in the image above.
To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screens VO pin (pin3).
click the images to enlarge

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

Code
/*
LiquidCrystal Library - TextDirection
Demonstrates the use a 16x2 LCD display. The

LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.

// reverse again at 's':


if (thisChar == 's') {
// go left for the next letter
lcd.leftToRight();
}
// reset at 'z':
if (thisChar > 'z') {
// go to (0,0):
lcd.home();
// start again at 0
thisChar = 'a';
}
// print the character
lcd.write(thisChar);
// wait a second:
delay(1000);
// increment the letter:
thisChar++;

This sketch demonstrates how to use


leftToRight() and rightToLeft()
to move the cursor.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)

Library originally added 18 Apr 2008


by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/LiquidCrystalTextDi
rection
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the
interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int thisChar = 'a';
void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(16, 2);
// turn on the cursor:
lcd.cursor();
}
void loop() {
// reverse directions at 'm':
if (thisChar == 'm') {
// go right for the next letter
lcd.rightToLeft();
}

LiquidCrystal - autoscroll()
The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch shows how to use
the autoscroll() and noAutoscroll()
methods to move all the text on the
display left or right.
autoscroll() moves all the text one space
to the left each time a letter is added
noAutoscroll() turns scrolling off
This sketch prints the
characters 0 to 9 with autoscroll off, then
moves the cursor to the bottom right,
turns autoscroll on, and prints them
again.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count
connector of the LCD screen, as you

can see in the image above.


To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to the LCD
screen's VO pin (pin3).
click the images to enlarge

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

Code
/*
LiquidCrystal Library - Autoscroll
Demonstrates the use a 16x2 LCD display. The

LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.

// set the cursor to (16,1):


lcd.setCursor(16,1);
// set the display to automatically scroll:
lcd.autoscroll();
// print from 0 to 9:
for (int thisChar = 0; thisChar < 10; thisChar++)
{
lcd.print(thisChar);
delay(500);
}
// turn off automatic scrolling
lcd.noAutoscroll();

This sketch demonstrates the use of the


autoscroll()
and noAutoscroll() functions to make new text
scroll or not.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)

// clear screen for the next loop:


lcd.clear();
}

Library originally added 18 Apr 2008


by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/LiquidCrystalAutosc
roll
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the
interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(16,2);
}
void loop() {
// set the cursor to (0,0):
lcd.setCursor(0, 0);
// print from 0 to 9:
for (int thisChar = 0; thisChar < 10; thisChar++)
{
lcd.print(thisChar);
delay(500);
}

LiquidCrystal - Serial Input


The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch accepts serial
input from a host computer and
displays it on the LCD. To use it,
upload the sketch, then open the Serial
Monitor and type some characters and
click Send. The text will appear on your
LCD.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count
connector of the LCD screen, as you
can see in the image above.
To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5

LCD D5 pin to digital pin 4


LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screen's VO pin (pin3).
click the images to enlarge

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

Code
/*
LiquidCrystal Library - Serial Input
Demonstrates the use a 16x2 LCD display. The

LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.

while (Serial.available() > 0) {


// display each character to the LCD
lcd.write(Serial.read());
}
}
}

This sketch displays text sent over the serial


port
(e.g. from the Serial Monitor) on an attached
LCD.

LiquidCrystal - setCursor()
The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch shows how to use
the setCursor() method to reposition
the cursor. To move the cursor, just call
setCursor() with a row and column
position. For example, for a 2x16
display:

The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe

lcd.setCursor(0, 0); // top left


lcd.setCursor(15, 0); // top right
lcd.setCursor(0, 1); // bottom left
lcd.setCursor(15, 1); // bottom right

This example code is in the public domain.

http://arduino.cc/en/Tutorial/LiquidCrystalSerial
*/
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the


interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup(){
// set up the LCD's number of columns and
rows:
lcd.begin(16, 2);
// initialize the serial communications:
Serial.begin(9600);
}
void loop()
{
// when characters arrive over the serial port...
if (Serial.available()) {
// wait a bit for the entire message to arrive
delay(100);
// clear the screen
lcd.clear();
// read all the available characters

Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count
connector of the LCD screen, as you
can see in the image above.
To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screens VO pin (pin3).
click the images to enlarge

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

Code
/*
LiquidCrystal Library - setCursor
Demonstrates the use a 16x2 LCD display. The

LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.

// loop over the columns:


for (int thisCol = 0; thisCol < numRows; thisCo
l++) {
// loop over the rows:
for (int thisRow = 0; thisRow < numCols; this
Row++) {
// set the cursor position:
lcd.setCursor(thisRow,thisCol);
// print the letter:
lcd.write(thisLetter);
delay(200);
}
}
}
}

This sketch prints to all the positions of the LCD


using the
setCursor(0 method:
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/LiquidCrystalSetCur
sor
*/
// include the library code:
#include <LiquidCrystal.h>

// these constants won't change. But you can


change the size of
// your LCD using them:
const int numRows = 2;
const int numCols = 16;

// initialize the library with the numbers of the


interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(numCols,numRows);
}
void loop() {
// loop from ASCII 'a' to ASCII 'z':
for (int thisLetter = 'a'; thisLetter <= 'z'; thisLette
r++) {

LiquidCrystal - scrollDisplayLeft() and


scrollDisplayRight()
The Liquid Crystal Library allows you to
control LCD displays that are
compatible with the
Hitachi HD44780 driver. There are
many of them out there, and you can
usually tell them by the 16-pin
interface.
This example sketch shows how to use
the scrollDisplayLeft() and scrollDisplayRight() m
ethods to reverse the direction the text
is flowing. It prints "Hello World!",
scrolls it offscreen to the left, then
offscreen to the right, then back to
home.
Hardware Required
Arduino Board
LCD Screen (compatible with
Hitachi HD44780 driver)
pin headers to solder to the LCD
display pins
10k Potentiometer
breadboard
hook-up wire
Circuit
Before wiring the LCD screen to your
Arduino we suggest to solder a pin
header strip to the 14 (or 16) pin count
connector of the LCD screen, as you
can see in the image above.
To wire your LCD screen to your
Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4

LCD D6 pin to digital pin 3


LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and
GND, with it's wiper (output) to LCD
screen's VO pin (pin3).
click the images to enlarge

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

Code
/*
LiquidCrystal Library - scrollDisplayLeft() and
scrollDisplayRight()

Demonstrates the use a 16x2 LCD display. The


LiquidCrystal
library works with all LCD displays that are
compatible with the
Hitachi HD44780 driver. There are many of
them out there, and you
can usually tell them by the 16-pin interface.

// scroll one position left:


lcd.scrollDisplayLeft();
// wait a bit:
delay(150);
}
// scroll 29 positions (string length + display
length) to the right
// to move it offscreen right:
for (int positionCounter = 0; positionCounter <
29; positionCounter++) {
// scroll one position right:
lcd.scrollDisplayRight();
// wait a bit:
delay(150);
}

This sketch prints "Hello World!" to the LCD and


uses the
scrollDisplayLeft() and scrollDisplayRight()
methods to scroll
the text.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)

// scroll 16 positions (display length + string


length) to the left
// to move it back to center:
for (int positionCounter = 0; positionCounter <
16; positionCounter++) {
// scroll one position left:
lcd.scrollDisplayLeft();
// wait a bit:
delay(150);
}

Library originally added 18 Apr 2008


by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe

// delay at the end of the full loop:


delay(1000);
}

SD Library

This example code is in the public domain.


http://arduino.cc/en/Tutorial/LiquidCrystalScroll
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the
interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and
rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
delay(1000);
}
void loop() {
// scroll 13 positions (string length) to the left
// to move it offscreen left:
for (int positionCounter = 0; positionCounter <
13; positionCounter++) {

Using the SD library to log data


This example shows how to use the SD
card Library to log data from three
analog sensors to a SD card.
Please click herefor more information
on the SD library.
Hardware Required
Three analog sensors
Arduino board
SD card board
Formatted SD card
Circuit

** CLK - pin 13
** CS - pin 4
created 24 Nov 2010
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SD.h>
// On the Ethernet Shield, CS is pin 4. Note that
even if it's not
// used as the CS pin, the hardware CS pin (10
on most Arduino boards,
// 53 on the Mega) must be left as an output or
the SD library
// functions will not work.
const int chipSelect = 4;

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

The code below is configured for use


with an Ethernet shield, which has an
onboard SD slot. In the setup(),
callSD.begin(), naming pin 4 as the CS
pin. This pin varies depending on the
make of shield or board.
In the loop(), a String is created to hold
the information from three analog
sensors. The code iterates through the
sensors, adding their data to the string.
Next, the file on the SD card is opened
by calling SD.open(). Once available, the
data is written to the card
whendataFile.println() is used. The file must
be closed with dataFile.close() to save the
information.
/*
SD card datalogger
This example shows how to log data from three
analog sensors
to an SD card using the SD library.
The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12

void setup()
{
// Open serial communications and wait for port
to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is
set to
// output, even if you don't use it:
pinMode(10, OUTPUT);
// see if the card is present and can be
initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}
void loop()
{
// make a string for assembling the data to log:
String dataString = "";
// read three sensors and append to the string:
for (int analogPin = 0; analogPin < 3; analogPin
++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2) {
dataString += ",";
}

}
// open the file. note that only one file can be
open at a time,
// so you have to close this one before opening
another.
File
dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}

Using the SD library to retrieve


information over a serial port
This example shows how to read a file
from a SD card using the SD library
and send it over the serial port.
Please click here for more information
on the SD library.
Hardware Required
Arduino board
Ethernet Shield (or other board with an
SD slot)
Formatted SD card with a file named
"datalog.txt" containing some text
Circuit

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

None, but the Arduino has to have the


Ethernet Shield and a USB cable
connected to the computer.
Code
The code below is configured for use
with an Ethernet shield, which has an
onboard SD slot. In the setup(),
callSD.begin(), naming pin 4 as the CS
pin. This pin varies depending on the
make of shield or board you are using.
On the SD card, there is a file named
"datalog.txt". In the loop(), the file is
opened when calling SD.open(). To send
the file serially to a computer,
use Serial.print(), reading the contents of
the file with SD.read().
/*
SD card file dump
This example shows how to read a file from the
SD card using the
SD library and send it over the serial port.
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4
created 22 December 2010
by Limor Fried
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SD.h>
// On the Ethernet Shield, CS is pin 4. Note that
even if it's not
// used as the CS pin, the hardware CS pin (10
on most Arduino boards,
// 53 on the Mega) must be left as an output or
the SD library
// functions will not work.
const int chipSelect = 4;
void setup()
{
// Open serial communications and wait for port
to open:
Serial.begin(9600);
while (!Serial) {

; // wait for serial port to connect. Needed for


Leonardo only
}
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is
set to
// output, even if you don't use it:
pinMode(10, OUTPUT);
// see if the card is present and can be
initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
// open the file. note that only one file can be
open at a time,
// so you have to close this one before opening
another.
File dataFile = SD.open("datalog.txt");
// if the file is available, write to it:
if (dataFile) {
while (dataFile.available()) {
Serial.write(dataFile.read());
}
dataFile.close();
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}
void loop()
{
}

Using the SD library to create and


remove files on a SD card
This example shows how to create and
destroy a file on a SD card.
Please click here for more information
on the SD library.
Hardware Required
Arduino board
Ethernet Shield (or other board with an
SD slot)
Formatted SD card
Circuit

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

None, but the Arduino has to have the


Ethernet Shield and a USB cable
connected to the computer.
Code
The code below is configured for use
with an Ethernet shield, which has an
onboard SD slot. In
the setup(), SD.begin()names pin 4 as the
CS pin. This pin varies depending on
the make of shield or board you are
using.
In the setup(), open a new file
with SD.open() named
"example.txt". FILE_WRITE enables read
and write access to the file, starting at
the end. In this example though,
immediately close the file by
calling myFile.close().
After checking to make sure the file
exists with SD.exists(), delete the file from
the card with SD.remove.
/*
SD card basic file example
This example shows how to create and destroy
an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

Serial.println("Removing example.txt...");
SD.remove("example.txt");

created Nov 2010


by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

if (SD.exists("example.txt")){
Serial.println("example.txt exists.");
}
else {
Serial.println("example.txt doesn't exist.");
}

This example code is in the public domain.


*/
#include <SD.h>

File myFile;

void loop()
{
// nothing happens after setup finishes.
}

void setup()
{
// Open serial communications and wait for port
to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
Serial.print("Initializing SD card...");
// On the Ethernet Shield, CS is pin 4. It's set
as an output by default.
// Note that even if it's not used as the CS pin,
the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega)
must be left as an output
// or the SD library functions will not work.
pinMode(10, OUTPUT);

Using the SD library to read and write


to a file on a SD card
his example shows how to read and
write data to and from an SD card.
Please click here for more information
on the SD library.
Hardware Required
Arduino board
Ethernet Shield (or other board with an
SD slot)
Formatted SD card
Circuit

if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
}
else {
Serial.println("example.txt doesn't exist.");
}
// open a new file and immediately close it:
Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE)
;
myFile.close();
// Check to see if the file exists:
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
}
else {
Serial.println("example.txt doesn't exist.");
}
// delete the file:

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

None, but the Arduino has to have the


Ethernet Shield and a USB cable
connected to the computer.
Code

The code below is configured for use


with an Ethernet shield, which has an
onboard SD slot. In the setup(), we
callSD.begin(), naming pin 4 as the CS
pin. This pin varies depending on the
make of shield or board you are using.
In setup(), create a new file
with SD.open() named
"test.txt". FILE_WRITE enables read and
write access to the file, starting at the
end. If a file "test.txt" was already on
the card, that file would be opened.
Name the instance of the opened file
"myFile".
Once opened, use myFile.println() to write
a string to the card, followed by a
carriage return. Once the content is
written, close the file.
Again, open the file with SD.open(). Once
opened, ask the Arduino to read the
contents of the file with SD.read() and
send them over the serial port. After all
the contents of the file are read, close
the file with SD.close().

Leonardo only
}
Serial.print("Initializing SD card...");
// On the Ethernet Shield, CS is pin 4. It's set
as an output by default.
// Note that even if it's not used as the CS pin,
the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega)
must be left as an output
// or the SD library functions will not work.
pinMode(10, OUTPUT);
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file. note that only one file can be
open at a time,
// so you have to close this one before opening
another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}

/*
SD card read/write
This example shows how to read and write data
to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

// re-open the file for reading:


myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// read from the file until there's nothing else in
it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}

This example code is in the public domain.


*/
#include <SD.h>
File myFile;
void setup()
{
// Open serial communications and wait for port
to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for

}
void loop()
{
// nothing happens after setup
}

Using the SD library to retrieve


information over a serial port
This example shows how to read
information about a SD card. The
example reports volume type, free
space and other information using the
SD library, sending it over the serial
port. Please click here for more
information on the SD library.
Hardware Required
Arduino board
Ethernet Shield (or other board with an
SD slot)
Formatted SD card
Circuit

amount of free space and space used


on the card.
/*
SD card test
This example shows how use the utility libraries
on which the'
SD library is based in order to get info about
your SD card.
Very useful for testing a card when you're not
sure whether its working or not.
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11 on Arduino
Uno/Duemilanove/Diecimila
** MISO - pin 12 on Arduino
Uno/Duemilanove/Diecimila
** CLK - pin 13 on Arduino
Uno/Duemilanove/Diecimila
** CS - depends on your SD card shield or
module.
Pin 4 used here for consistency with other
Arduino examples
created 28 Mar 2011
by Limor Fried
modified 9 Apr 2012
by Tom Igoe
*/
// include the SD library:
#include <SD.h>
// set up variables using the SD utility library
functions:
Sd2Card card;
SdVolume volume;
SdFile root;

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

None, but the Arduino has to have the


Ethernet Shield and a USB cable
connected to the computer.
Code
The code below is configured for use
with an Ethernet shield, which has an
onboard SD slot. In the setup(),
callSD.begin(), naming pin 4 as the CS
pin. This pin varies depending on the
make of shield or board you are using.
The code uses some undocumented
utility libraries to report information
about the SD card. This information
includes formatting (FAT16 or FAT32)
and file structure, as well as the

// change this to match your SD shield or


module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = 4;
void setup()
{
// Open serial communications and wait for port
to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
Serial.print("\nInitializing SD card...");
// On the Ethernet Shield, CS is pin 4. It's set
as an output by default.

// Note that even if it's not used as the CS pin,


the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega)
must be left as an output
// or the SD library functions will not work.
pinMode(10, OUTPUT); // change this to 53
on a mega
// we'll use the initialization code from the utility
libraries
// since we're just testing if the card is working!
if (!card.init(SPI_HALF_SPEED, chipSelect)) {
Serial.println("initialization failed. Things to
check:");
Serial.println("* is a card is inserted?");
Serial.println("* Is your wiring correct?");
Serial.println("* did you change the chipSelect
pin to match your shield or module?");
return;
} else {
Serial.println("Wiring is correct and a card is
present.");
}
// print the type of card
Serial.print("\nCard type: ");
switch(card.type()) {
case SD_CARD_TYPE_SD1:
Serial.println("SD1");
break;
case SD_CARD_TYPE_SD2:
Serial.println("SD2");
break;
case SD_CARD_TYPE_SDHC:
Serial.println("SDHC");
break;
default:
Serial.println("Unknown");
}
// Now we will try to open the 'volume'/'partition'
- it should be FAT16 or FAT32
if (!volume.init(card)) {
Serial.println("Could not find FAT16/FAT32
partition.\nMake sure you've formatted the
card");
return;
}
// print the type and size of the first FAT-type
volume
uint32_t volumesize;
Serial.print("\nVolume type is FAT");
Serial.println(volume.fatType(), DEC);
Serial.println();
volumesize = volume.blocksPerCluster(); //
clusters are collections of blocks
volumesize *= volume.clusterCount();
//
we'll have a lot of clusters

volumesize *= 512;
// SD card
blocks are always 512 bytes
Serial.print("Volume size (bytes): ");
Serial.println(volumesize);
Serial.print("Volume size (Kbytes): ");
volumesize /= 1024;
Serial.println(volumesize);
Serial.print("Volume size (Mbytes): ");
volumesize /= 1024;
Serial.println(volumesize);
Serial.println("\nFiles found on the card (name,
date and size in bytes): ");
root.openRoot(volume);
// list all files in the card with date and size
root.ls(LS_R | LS_DATE | LS_SIZE);
}
void loop(void) {
}

Servo library
This library allows an Arduino board to
control RC (hobby) servo motors. Servos
have integrated gears and a shaft that can
be precisely controlled. Standard servos
allow the shaft to be positioned at various
angles, usually between 0 and 180 degrees.
Continuous rotation servos allow the rotation
of the shaft to be set to various speeds.
The Servo library supports up to 12 motors
on most Arduino boards and 48 on the
Arduino Mega. On boards other than the
Mega, use of the library disables
analogWrite() (PWM) functionality on pins 9
and 10, whether or not there is a Servo on
those pins. On the Mega, up to 12 servos
can be used without interfering with PWM
functionality; use of 12 to 23 motors will
disable PWM on pins 11 and 12.
Circuit

Servo motors have three wires: power,


ground, and signal. The power wire is
typically red, and should be connected to
the 5V pin on the Arduino board. The
ground wire is typically black or brown and
should be connected to a ground pin on the
Arduino board. The signal pin is typically
yellow, orange or white and should be
connected to a digital pin on the Arduino
board. Note that servos draw considerable
power, so if you need to drive more than
one or two, you'll probably need to power
them from a separate supply (i.e. not the

+5V pin on your Arduino). Be sure to


connect the grounds of the Arduino and
external power supply together.

Functions
attach()
write()
writeMicroseconds()
read()
attached()
detach()

attach()
Description
Attach the Servo variable to a pin. Note
that in Arduino 0016 and earlier, the
Servo library supports only servos on
only two pins: 9 and 10.
Syntax
servo.attach(pin)
servo.attach(pin, min, max)
Parameters
servo: a variable of type Servo
pin: the number of the pin that the
servo is attached to
min (optional): the pulse width, in
microseconds, corresponding to the
minimum (0-degree) angle on the servo
(defaults to 544)
max (optional): the pulse width, in
microseconds, corresponding to the
maximum (180-degree) angle on the
servo (defaults to 2400)
Example
#include <Servo.h>
Servo myservo;
void setup()
{
myservo.attach(9);
}
void loop() {}

write()
Description
Writes a value to the servo, controlling
the shaft accordingly. On a standard
servo, this will set the angle of the shaft
(in degrees), moving the shaft to that
orientation. On a continuous rotation
servo, this will set the speed of the
servo (with 0 being full-speed in one

direction, 180 being full speed in the


other, and a value near 90 being no
movement).
Syntax
servo.write(angle)
Parameters
servo: a variable of type Servo
angle: the value to write to the servo,
from 0 to 180
Example
#include <Servo.h>
Servo myservo;
void setup()
{
myservo.attach(9);
myservo.write(90); // set servo to mid-point
}
void loop() {}

writeMicroseconds()
Description
Writes a value in microseconds (uS) to
the servo, controlling the shaft
accordingly. On a standard servo, this
will set the angle of the shaft. On
standard servos a parameter value of
1000 is fully counter-clockwise, 2000 is
fully clockwise, and 1500 is in the
middle.
Note that some manufactures do not
follow this standard very closely so that
servos often respond to values
between 700 and 2300. Feel free to
increase these endpoints until the
servo no longer continues to increase
its range. Note however that attempting
to drive a servo past its endpoints
(often indicated by a growling sound) is
a high-current state, and should be
avoided.
Continuous-rotation servos will respond
to the writeMicrosecond function in an
analogous manner to the writefunction.
Syntax
servo.writeMicroseconds(uS)
Parameters
servo: a variable of type Servo
uS: the value of the parameter in
microseconds (int)

Example
#include <Servo.h>
Servo myservo;
void setup()
{
myservo.attach(9);
myservo.writeMicroseconds(1500); // set servo to
mid-point
}
void loop() {}

read()
Description
Read the current angle of the servo
(the value passed to the last call to
write()).
Syntax
servo.read()
Parameters
servo: a variable of type Servo
Returns
The angle of the servo, from 0 to 180
degrees.

attached()
Description
Check whether the Servo variable is
attached to a pin.
Syntax
servo.attached()
Parameters
servo: a variable of type Servo
Returns
true if the servo is attached to pin; false
otherwise.

Control the position of a RC


(hobby) servo motor with your Arduino
and a potentiometer.
This example makes use of the
Arduino servo library.
Hardware Required
Arduino Board
(1) Servo Motor
(1) Potentiometer
hook-up wire
Circuit
Servo motors have three wires: power,
ground, and signal. The power wire is
typically red, and should be connected
to the 5V pin on the Arduino board. The
ground wire is typically black or brown
and should be connected to a ground
pin on the Arduino board. The signal
pin is typically yellow or orange and
should be connected to pin 9 on the
Arduino board.
The potentiometer should be wired so
that its two outer pins are connected to
power (+5V) and ground, and its middle
pin is connected to analog input 0 on
the Arduino.
click the images to enlarge

detach()
Description
Detach the Servo variable from its pin.
If all Servo variables are detached,
then pins 9 and 10 can be used for
PWM output with analogWrite().
Syntax
servo.detach()
Parameters
servo: a variable of type Servo
Knob

images developed using Fritzing. For more


circuit examples, see the Fritzing project page

Schematic

value of the potentiometer (value between 0 and


1023)
val = map(val, 0, 1023, 0, 179); // scale it to
use it with the servo (value between 0 and 180)
myservo.write(val);
// sets the servo
position according to the scaled value
delay(15);
// waits for the servo
to get there
}

Sweep
Sweeps the shaft of a RC servo
motor back and forth across 180
degrees.
This example makes use of the
Arduino servo library.
Hardware Required
Arduino Board
(1) Servo Motor
hook-up wire
Circuit
Servo motors have three wires: power,
ground, and signal. The power wire is
typically red, and should be connected
to the 5V pin on the Arduino board. The
ground wire is typically black or brown
and should be connected to a ground
pin on the Arduino board. The signal
pin is typically yellow, orange or white
and should be connected to pin 9 on
the Arduino board.
click the images to enlarge

Code
// Controlling a servo position using a
potentiometer (variable resistor)
// by Michal Rinott <http://people.interactionivrea.it/m.rinott>
#include <Servo.h>
Servo myservo; // create servo object to control
a servo
int potpin = 0; // analog pin used to connect the
potentiometer
int val; // variable to read the value from the
analog pin
void setup()
{
myservo.attach(9); // attaches the servo on pin
9 to the servo object
}
void loop()
{
val = analogRead(potpin);

// reads the

images developed using Fritzing. For more


circuit examples, see the Fritzing project page

Schematic

void loop()
{
for(pos = 0; pos < 180; pos += 1) // goes from
0 degrees to 180 degrees
{
// in steps of 1 degree
myservo.write(pos);
// tell servo to go
to position in variable 'pos'
delay(15);
// waits 15ms for the
servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from
180 degrees to 0 degrees
{
myservo.write(pos);
// tell servo to go
to position in variable 'pos'
delay(15);
// waits 15ms for the
servo to reach the position
}
}

SPI library
This library allows you to communicate with
SPI devices, with the Arduino as the master
device.

A Brief Introduction to the Serial


Peripheral Interface (SPI)

Code
// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.

Serial Peripheral Interface (SPI) is a


synchronous serial data protocol used by
microcontrollers for communicating with one
or more peripheral devices quickly over
short distances. It can also be used for
communication between two
microcontrollers.
With an SPI connection there is always one
master device (usually a microcontroller)
which controls the peripheral devices.
Typically there are three lines common to all
the devices:
MISO (Master In Slave Out) - The Slave line for

sending data to the master,


MOSI (Master Out Slave In) - The Master line for

#include <Servo.h>
Servo myservo; // create servo object to control
a servo
// a maximum of eight servo objects
can be created
int pos = 0;
position

// variable to store the servo

void setup()
{
myservo.attach(9); // attaches the servo on pin
9 to the servo object
}

sending data to the peripherals,


SCK (Serial Clock) - The clock pulses which

synchronize data transmission generated by the


master

and one line specific for every device:


SS (Slave Select) - the pin on each device that

the master can use to enable and disable


specific devices.

When a device's Slave Select pin is low, it


communicates with the master. When it's
high, it ignores the master. This allows you
to have multiple SPI devices sharing the
same MISO, MOSI, and CLK lines.
To write code for a new SPI device you
need to note a few things:
Is data shifted in Most Significant Bit (MSB) or

Least Significant Bit (LSB) first? This is

controlled by the SPI.setBitOrder() function.


Is the data clock idle when high or low? Are
samples on the rising or falling edge of clock
pulses? These modes are controlled by
theSPI.setDataMode() function.
What speed is the SPI running at? This is
controlled by theSPI.setClockDivider() function.

The SPI standard is loose and each device


implements it a little differently. This means
you have to pay special attention to the
device's datasheet when writing your code.
Generally speaking, there are four modes of
transmission. These modes control whether
data is shifted in and out on the rising or
falling edge of the data clock signal (called
the clock phase), and whether the clock is
idle when high or low (called the
clock polarity). The four modes combine
polarity and phase according to this table:
Mode
SPI_MODE0
SPI_MODE1
SPI_MODE2
SPI_MODE3

Clock
Polarity
(CPOL)
0
0
1
1

Clock
Phase
(CPHA)
0
1
0
1

Connections
The following table display on which pins the
SPI lines are broken out on the different
Arduino boards:

Uno
or
Due
mila
nove
Meg

M
O
SI

M
IS
O

S
C
K

1
1
or
IC
S
P4
5

1
2
or
IC
S
P1
5

1
3
or
IC
S
P3
5

S
S
(sl
av
e)

Leon
ardo

Due

1
or
IC
S
P4
IC
S
P4
IC
S
P4

0
or
IC
S
P1
IC
S
P1
IC
S
P1

2
or
IC
S
P3
IC
S
P3
IC
S
P3

4,
10,
52

Note that MISO, MOSI, and SCK are


available in a consistent physical location on
the ICSP header; this is useful, for example,
in designing a shield that works on every
board.

Note about Slave Select (SS) pin on AVR


based boards

The SPI.setDataMode() function lets you set


the mode to control clock polarity and
phase.
Every SPI device has a maximum allowed
speed for SPI Bus. The
SPI.setClockDivider() allows you to change
the clock speed to make your device
working properly (default is 4MHz).
Once you have your SPI parameters set
correctly you just need to figure which
registers in your device control which
functions, and you're good to go. This will be
explained in the data sheet for your device.
For more on SPI, see Wikipedia's page on
SPI.

Ardu
ino
Boar
d

a128
0 or
Meg
a256
0

SS
(m
ast
er)

10

53

All AVR based boards have an SS pin that


is useful when they act as a slavecontrolled
by an external master. Since this library
supports only master mode, this pin should
be set always as OUTPUT otherwise the
SPI interface could be put automatically into
slave mode by hardware, rendering the
library inoperative.
It is, however, possible to use any pin as the
Slave Select (SS) for the devices. For
example, the Arduino Ethernet shield uses
pin 4 to control the SPI connection to the onboard SD card, and pin 10 to control the
connection to the Ethernet controller.
Extended SPI functionality for the Due

The Arduino Due's SPI interface works


differently than any other Arduino boards.
The library can be used on the Due with the
same methods available to other Arduino
boards or using the extended methods. The
extended methods exploits the
the SAM3X hardware and allows some
interesting features like:
automatic handling of the device slave selection.
automatic handling of different device

configurations (clock speed, data mode, etc) so


every device can have its own configuration
automatically selected.

Arduino Due has three exposed pins for the


devices Slave Select (SS) lines (pins 4, 10,
and 52).

device
SS
pin

begin()
Description
Initializes the SPI bus by setting SCK,
MOSI, and SS to outputs, pulling SCK
and MOSI low, and SS high.
Extended method for Arduino Due
If you specify one of the Arduino Due's
Slave Select (SS) pin in the call to
SPI.begin(), the pin is configured to be
directly managed by the SPI interface.
Note that once the pin is configured,
you can't use it anymore as a general
I/O, unless you call the SPI.end()
method on the same pin.
The only pins that can be configured to
be managed by SPI interface are the
Arduino Due's Slave Select pins: 4, 10,
52 and 54 (correspond to A0).
More info on extended methods: Due
Extended SPI usage
Syntax
SPI.begin()
SPI.begin(slaveSelectPin)

(Arduino
Due
only)

Parameters
slaveSelectPin:

slave
device
SS
pin

(Arduino
Due
only)

end()
Description
Disables the SPI bus (leaving pin
modes unchanged).
Extended method for Arduino Due
If you specify one of the Arduino Due's
Slave Select (SS) pin in the call to
end(), the specified pin is disconnected
from the SPI interface and is available
again as a general I/O. More info on
extended methods: Due Extended SPI
usage
Syntax
(Arduino
Due
only)

Parameters
slaveSelectPin:

slave

Returns
None

setBitOrder()
Description
Sets the order of the bits shifted out of
and into the SPI bus, either LSBFIRST
(least-significant bit first) or MSBFIRST
(most-significant bit first).
Extended method for Arduino Due
If you specify one of the Arduino Due's
Slave Select (SS) pin in the call to
setBitOrder(), the bit order setting is
applied only to the device connected to
the specified SS pin. More info on
extended methods: Due Extended SPI
usage
Syntax
SPI.setBitOrder(order)
SPI.setBitOrder(slaveSelectPin,
order)

(Arduino
Due
only)

Parameters
order: either LSBFIRST or MSBFIRST
Returns
None

setClockDivider()

Returns
None

SPI.end()
SPI.end(slaveSelectPin)

Due
only)

(Arduino

Description
Sets the SPI clock divider relative to
the system clock. On AVR based
boards, the dividers available are 2, 4,
8, 16, 32, 64 or 128. The default setting
is SPI_CLOCK_DIV4, which sets the
SPI clock to one-quarter the frequency
of the system clock (4 Mhz for the
boards at 16 MHz).
Arduino Due
On the Due, the system clock can be
divided by values from 1 to 255. The
default value is 21, which sets the clock
to 4MHz like other Arduino boards.
Extended method for Arduino Due
If you specify one of the Arduino Due's
Slave Select (SS) pin in the call to
setClockDivider(), the clock setting is
applied only to the device connected to
the specified SS pin. More info on

extended methods: Due Extended SPI


usage
Syntax
SPI.setClockDivider(divider)
SPI.setClockDivider(slaveSelectPi
n, divider)

(Arduin
o Due
only)

Parameters
divider:

slaveSelec
tPin:

SPI_CLOCK_DIV2
SPI_CLOCK_DIV4
SPI_CLOCK_DIV8
SPI_CLOCK_DIV1
6
SPI_CLOCK_DIV3
2
SPI_CLOCK_DIV6
4
SPI_CLOCK_DIV1
28
slave device SS
pin

divider:

a number from 1
to 255

(On
AVR
board
s)

(Ardui
no
Due
only)
(Ardui
no
Due
only)

Returns
None

setDataMode()
Description
Sets the SPI data mode: that is, clock
polarity and phase. See the Wikipedia
article on SPI for details.
Extended method for Arduino Due
If you specify one of the Arduino Due's
Slave Select (SS) pin in the call to
setDataMode(), the data mode setting
is applied only to the device connected
to the specified SS pin. More info on
extended methods: Due Extended SPI
usage
Syntax
SPI.setDataMode(mode)
SPI.setDataMode(slaveSelectPin,
mode)

(Arduino
Due
only)

Parameters
mode:

slaveSelectPi
n

SPI_MODE0
SPI_MODE1
SPI_MODE2
SPI_MODE3
slave device
SS pin

(Arduin
o Due
only)

Returns
None

transfer()
Description
Transfers one byte over the SPI bus,
both sending and receiving.
Extended method for Arduino Due
If you specify one of the Arduino Due's
Slave Select (SS) pin in the call to
SPI.transfer(), the specified pin is
activated (pulled low) before the
transfer occurs and deactivated (pulled
high) when the transfer is finished.
You can use an additional
SPI_CONTINUE or SPI_LAST
parameter to manage the Slave Select
line after the transfer. SPI_CONTINUE
keeps the specified SS pin active (low)
after the transfer to allow the send of
additional bytes via the transfer()
function in the same SPI transaction.
The last byte to be transferred should
be accompanied by the SPI_LAST
parameter. By default, if you don't
specify a third parameter, SPI_LAST is
used. When a transfer is complete with
SPI_LAST, the slave select pin returns
inactive (high).
More info on extended methods: Due
Extended SPI usage
Syntax
SPI.transfer(val)
SPI.transfer(slaveSelectPin,
val)
SPI.transfer(slaveSelectPin,
val, transferMode)

(Arduino
Due
only)
(Arduino
Due
only)

Parameters
val:

the byte to send


out over the bus

slaveSelect
Pin:

slave device SS
pin

transferMo
de:

SPI_CONTINUE:

keeps the SS pin


low, allowing a
subsequent byte
transfer.
SPI_LAST: defa
ult if not
specified the SS
pin returns to

(Arduin
o Due
only)
(Optio
nal,
Arduin
o Due
only)

high after one


byte has been
transferred.

A single byte transfer to a device on pin


4 could look like this :
void loop(){
byte response = SPI.transfer(4, 0xFF);
}
[Get Code]

Returns
the byte read from the bus.
Extended SPI library usage with the
Due
On the Arduino Due, the SAM3X has
advanced SPI capabilities. It is possible
to use these extended methods, or the
AVR-based ones.
The extended API can use pins 4, 10,
and 52 for CS.
Use
You must specify each pin you wish to
use as CS for the SPI devices.
It is possible for the Due to
automatically handle the chip selection
between multiple devices sharing the
SPI bus. Each device may have also
different attribues such as speed and
datamode.
If using multiple devices with different
CS pins, you'll need to declare those
pins in setup(). In the following
example, there are two devices that
share the SPI MISO, MOSI, and SCK
pins. One device CS is attached to pin
4, the other to pin 10.
void setup(){
// initialize the bus for a device on pin 4
SPI.begin(4);
// initialize the bus for a device on pin 10
SPI.begin(10);
}
[Get Code]

Once a pin has been declared as a CS


pin, it's possible to change its default
behaviors as well. For example, if the
devices run at different clock speeds,
the setup() may look like this :
void setup(){
// initialize the bus for the device on pin 4
SPI.begin(4);
// Set clock divider on pin 4 to 21
SPI.setClockDivider(4, 21);
// initialize the bus for the device on pin 10
SPI.begin(10);
// Set clock divider on pin 10 to 84
SPI.setClockDivider(10, 84);
}
[Get Code]

In the above, 0xFF is sent to the SPI


device on pin 4 and the data coming
from MISO is saved inside the
variableresponse. The chip selection is
handled automatically by the SPI
controller, the transfer command
implies the following:
Select device by setting pin 4 to LOW
Send 0xFF through the SPI bus and
return the byte received
Deselect device by setting pin 4 to
HIGH
It's possible to send more than one
byte in a transaction by telling the the
transfer command to not deselect the
SPI device after the transfer :
void loop(){
//transfer 0x0F to the device on pin 10, keep the
chip selected
SPI.transfer(10, 0xF0, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, keep the
chip selected
SPI.transfer(10, 000, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, store
byte received in response1, keep the chip
selected
byte response1 = SPI.transfer(10, 000, SPI_C
ONTINUE);
//transfer 0x00 to the device on pin 10, store
byte received in response2, deselect the chip
byte response2 = SPI.transfer(10, 000);
}
[Get Code]

The parameter SPI_CONTINUE


ensures that chip selection is keep
active between transfers. On the last
transfer SPI_CONTINUE is not
specified as it's the last byte
transferred.
See the individual reference pages
for setClockDivider(), setDataMode(), tr
ansfer(), setBitOrder() for proper syntax
when using the extended methods.
NB : once SPI.begin() is called, the
declared pin will not be available as a
general purpose I/O pin

Extended SPI library usage with the


Due
On the Arduino Due, the SAM3X has
advanced SPI capabilities. It is possible
to use these extended methods, or the
AVR-based ones.
The extended API can use pins 4, 10,
and 52 for CS.
Use
You must specify each pin you wish to
use as CS for the SPI devices.
It is possible for the Due to
automatically handle the chip selection
between multiple devices sharing the
SPI bus. Each device may have also
different attribues such as speed and
datamode.
If using multiple devices with different
CS pins, you'll need to declare those
pins in setup(). In the following
example, there are two devices that
share the SPI MISO, MOSI, and SCK
pins. One device CS is attached to pin
4, the other to pin 10.
void setup(){
// initialize the bus for a device on pin 4
SPI.begin(4);
// initialize the bus for a device on pin 10
SPI.begin(10);
}
[Get Code]

Once a pin has been declared as a CS


pin, it's possible to change its default
behaviors as well. For example, if the
devices run at different clock speeds,
the setup() may look like this :
void setup(){
// initialize the bus for the device on pin 4
SPI.begin(4);
// Set clock divider on pin 4 to 21
SPI.setClockDivider(4, 21);
// initialize the bus for the device on pin 10
SPI.begin(10);
// Set clock divider on pin 10 to 84
SPI.setClockDivider(10, 84);
}
[Get Code]

A single byte transfer to a device on pin


4 could look like this :
void loop(){
byte response = SPI.transfer(4, 0xFF);
}
[Get Code]

In the above, 0xFF is sent to the SPI


device on pin 4 and the data coming
from MISO is saved inside the
variableresponse. The chip selection is
handled automatically by the SPI
controller, the transfer command
implies the following:
Select device by setting pin 4 to LOW
Send 0xFF through the SPI bus and
return the byte received
Deselect device by setting pin 4 to
HIGH
It's possible to send more than one
byte in a transaction by telling the the
transfer command to not deselect the
SPI device after the transfer :
void loop(){
//transfer 0x0F to the device on pin 10, keep the
chip selected
SPI.transfer(10, 0xF0, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, keep the
chip selected
SPI.transfer(10, 000, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, store
byte received in response1, keep the chip
selected
byte response1 = SPI.transfer(10, 000, SPI_C
ONTINUE);
//transfer 0x00 to the device on pin 10, store
byte received in response2, deselect the chip
byte response2 = SPI.transfer(10, 000);
}
[Get Code]

The parameter SPI_CONTINUE


ensures that chip selection is keep
active between transfers. On the last
transfer SPI_CONTINUE is not
specified as it's the last byte
transferred.
See the individual reference pages
for setClockDivider(), setDataMode(), tr
ansfer(), setBitOrder() for proper syntax
when using the extended methods.
NB : once SPI.begin() is called, the
declared pin will not be available as a
general purpose I/O pin
Controlling a Digital Potentiometer
Using SPI
Examples > SPI LIbrary
In this tutorial you will learn how to
control the AD5206 digital
potentiometer using Serial Peripheral

Interface (SPI). For an explanation of


SPI see the SPI EEPROM tutorial.
Digital potentiometers are useful when
you need to vary the resistance in a
circuit electronically rather than by
hand. Example applications include
LED dimming, audio signal conditioning
and tone generation. In this example
we will use a six channel digital
potentiometer to control the brightness
of six LEDs. The steps we will cover for
implementing SPI communication can
be modified for use with most other SPI
devices.
Hardware Required
AD5206 Digital Potentiometer
Arduino Microcontroller Module
6 Light Emitting Diodes (LEDs)
6 220 ohm resistors
Hookup Wire
Introduction to the AD5206 Digital
Potentiometer
Click for for the AD5206's datasheet.

The AD5206 is a 6 channel digital


potentiometer. This means it has six
variable resistors (potentiometers) built
in for individual electronic control.
There are three pins on the chip for
each of the six internal variable
resistors, and they can be interfaced
with just as you would use a
mechanical potentiometer. The
individual variable resistor pins are
labeled Ax, Bx and Wx, ie. A1, B1 and
W1. For example, in this tutorial we will
be using each variable resistor as a

voltage divider by pulling one side pin


(pin B) high, pulling another side pin
(pin A) low and taking the variable
voltage output of the center pin (Wiper).
In this case, the AD5206 provides a
maximum resistance of 10K ohms,
delivered in 255 steps (255 being the
max, 0 being the least).
Circuit

image developed using Fritzing. For


more circuit examples, see the Fritzing
project page
Schematic

with the resistance value for the


channel (0 - 255).
The circuit:
* All A pins of AD5206 connected to +5V
* All B pins of AD5206 connected to ground
* An LED and a 220-ohm resisor in series
connected from each W pin to ground
* CS - to digital pin 10 (SS pin)
* SDI - to digital pin 11 (MOSI pin)
* CLK - to digital pin 13 (SCK pin)
created 10 Aug 2010
by Tom Igoe
Thanks to Heather Dewey-Hagborg for the
original tutorial, 2005
*/
// inslude the SPI library:
#include <SPI.h>
// set pin 10 as the slave select for the digital
pot:
const int slaveSelectPin = 10;
void setup() {
// set the slaveSelectPin as an output:
pinMode (slaveSelectPin, OUTPUT);
// initialize SPI:
SPI.begin();
}

Code
/*
Digital Pot Control
This example controls an Analog Devices
AD5206 digital potentiometer.
The AD5206 has 6 potentiometer channels.
Each channel's pins are labeled
A - connect this to voltage
W - this is the pot's wiper, which changes when
you set it
B - connect this to ground.
The AD5206 is SPI-compatible,and to
command it, you send two bytes,
one with the channel number (0 - 5) and one

void loop() {
// go through the six channels of the digital pot:
for (int channel = 0; channel < 6; channel++) {
// change the resistance on this channel from
min to max:
for (int level = 0; level < 255; level++) {
digitalPotWrite(channel, level);
delay(10);
}
// wait a second at the top:
delay(100);
// change the resistance on this channel from
max to min:
for (int level = 0; level < 255; level++) {
digitalPotWrite(channel, 255 - level);
delay(10);
}
}
}
void digitalPotWrite(int address, int value) {
// take the SS pin low to select the chip:
digitalWrite(slaveSelectPin,LOW);
// send in the address and value via SPI:
SPI.transfer(address);

SPI.transfer(value);
// take the SS pin high to de-select the chip:
digitalWrite(slaveSelectPin,HIGH);
}

SoftwareSerial Library

The Arduino hardware has built-in


support for serial communication on
pins 0 and 1 (which also goes to the
computer via the USB connection). The
native serial support happens via a
piece of hardware (built into the chip)
called a UART. This hardware allows
the Atmega chip to receive serial
communication even while working on
other tasks, as long as there room in
the 64 byte serial buffer.
The SoftwareSerial library has been
developed to allow serial
communication on other digital pins of
the Arduino, using software to replicate
the functionality (hence the name
"SoftwareSerial"). It is possible to have
multiple software serial ports with
speeds up to 115200 bps. A parameter
enables inverted signaling for devices
which require that protocol.
The version of SoftwareSerial included
in 1.0 and later is based on
the NewSoftSerial library by Mikal Hart.
Limitations
The library has the following known
limitations:
If using multiple software serial ports,
only one can receive data at a time.
Not all pins on the Mega and Mega
2560 support change interrupts, so only
the following can be used for RX: 10,
11, 12, 13, 14, 15, 50, 51, 52, 53, A8
(62), A9 (63), A10 (64), A11 (65), A12
(66), A13 (67), A14 (68), A15 (69).
Not all pins on the Leonardo support
change interrupts, so only the following
can be used for RX: 8, 9, 10, 11, 14
(MISO), 15 (SCK), 16 (MOSI).
If your project requires simultaneous
data flows, see Paul
Stoffregen's AltSoftSerial
library. AltSoftSerial overcomes a
number of other issues with the
core SoftwareSerial, but has it's own

limitations. Refer to the AltSoftSerial


site for more information.
Example
/*
Software serial multple serial test
Receives from the hardware serial, sends to
software serial.
Receives from software serial, sends to
hardware serial.
The circuit:
* RX is digital pin 10 (connect to TX of other
device)
* TX is digital pin 11 (connect to RX of other
device)
Note:
Not all pins on the Mega and Mega 2560
support change interrupts,
so only the following can be used for RX:
10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65,
66, 67, 68, 69
Not all pins on the Leonardo support change
interrupts,
so only the following can be used for RX:
8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
created back in the mists of time
modified 25 May 2012
by Tom Igoe
based on Mikal Hart's example
This example code is in the public domain.
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
// Open serial communications and wait for port
to open:
Serial.begin(57600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
Serial.println("Goodnight moon!");
// set the data rate for the SoftwareSerial port
mySerial.begin(4800);
mySerial.println("Hello, world?");
}
void loop() // run over and over
{

if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());

Returns
the number of bytes available to read
Example

}
[Get Code]

Functions
SoftwareSerial()
available()
begin()
isListening()
overflow()
peek()
read()
print()
println()
listen()
write()

SoftwareSerial(rxPin, txPin)
Description
A call to SoftwareSerial(rxPin, txPin)
creates a new SoftwareSerial object,
whose name you need to provide as in
the example below.
You need to call SoftwareSerial.begin()
to enable communication.
Parameters
rxPin: the pin on which to receive serial
data
txPin: the pin on which to transmit
serial data
Example
#define rxPin 2
#define txPin 3
// set up a new serial port
SoftwareSerial
mySerial = SoftwareSerial(rxPin, txPin);

SoftwareSerial: available()
Description
Get the number of bytes (characters)
available for reading from a software
serial port. This is data that's already
arrived and stored in the serial receive
buffer.
Syntax
mySerial.available()
Parameters
none

// include the SoftwareSerial library so you can


use its functions:
#include <SoftwareSerial.h>
#define rxPin 10
#define txPin 11
// set up a new serial port
SoftwareSerial
mySerial = SoftwareSerial(rxPin, txPin);
void setup() {
// define pin modes for tx, rx:
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
}
void loop() {
if (mySerial.available()>0){
mySerial.read();
}
}

SoftwareSerial: begin(speed)
Description
Sets the speed (baud rate) for the
serial communication. Supported baud
rates are 300, 600, 1200, 2400, 4800,
9600, 14400, 19200, 28800, 31250,
38400, 57600, and 115200.
Parameters
speed: the baud rate (long)
Returns
none
Example
// include the SoftwareSerial library so you can
use its functions:
#include <SoftwareSerial.h>
#define rxPin 10
#define txPin 11
// set up a new serial port
SoftwareSerial
mySerial = SoftwareSerial(rxPin, txPin);
void setup() {
// define pin modes for tx, rx:
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
}

void loop() {
// ...
}

SoftwareSerial: isListening()
Description
Tests to see if requested software
serial port is actively listening.
Syntax
mySerial.isListening()
Parameters
none
Returns
boolean
Example
#include <SoftwareSerial.h>
// software serial : TX = digital pin 10, RX =
digital pin 11
SoftwareSerial portOne(10,11);
void setup()
{
// Start the hardware serial port
Serial.begin(9600);
// Start software serial port
portOne.begin(9600);
}
void loop()
{
if (portOne.isListening()) {
Serial.println("Port One is listening!");
}

SoftwareSerial: overflow()
Description
Tests to see if a software serial buffer
overflow has occurred. Calling this
function clears the overflow flag,
meaning that subsequent calls will
return false unless another byte of data
has been received and discarded in the
meantime.
The software serial buffer can hold 64
bytes.
Syntax
mySerial.overflow()
Parameters
none
Returns
boolean

Example
#include <SoftwareSerial.h>
// software serial : TX = digital pin 10, RX =
digital pin 11
SoftwareSerial portOne(10,11);
void setup()
{
// Start the hardware serial port
Serial.begin(9600);
// Start software serial port
portOne.begin(9600);
}
void loop()
{
if (portOne.overflow()) {
Serial.println("SoftwareSerial overflow!");
}

SoftwareSerial: peek
Description
Return a character that was received
on the RX pin of the software serial
port. Unlike read(), however,
subsequent calls to this function will
return the same character.
Note that only
one SoftwareSerial instance can
receive incoming data at a time (select
which one with the listen()function).
Parameters
none
Returns
the character read, or -1 if none is
available
Example
SoftwareSerial mySerial(10,11);
void setup()
{
mySerial.begin(9600);
}
void loop()
{
char c = mySerial.peek();
}

SoftwareSerial: read
Description
Return a character that was received
on the RX pin of the software serial
port. Note that only

one SoftwareSerialinstance can receive


incoming data at a time (select which
one with the listen() function).
Parameters
none
Returns
the character read, or -1 if none is
available
Example
SoftwareSerial mySerial(10,11);
void setup()
{
mySerial.begin(9600);
}
void loop()
{
char c = mySerial.read();
}

SoftwareSerial: print(data)
Description
Prints data to the transmit pin of the
software serial port. Works the same as
the Serial.print() function.
Parameters
vary, see Serial.print() for details
Returns
byte
print() will return the number of bytes
written, though reading that number is
optional
Example
SoftwareSerial serial(10,11);
int analogValue;
void setup()
{
serial.begin(9600);
}
void loop()
{
// read the analog input on pin 0:
analogValue = analogRead(A0);
// print it out in many formats:
serial.print(analogValue);
// print as an
ASCII-encoded decimal
serial.print("\t");
// print a tab
character
serial.print(analogValue, DEC); // print as an
ASCII-encoded decimal
serial.print("\t");
// print a tab
character

serial.print(analogValue, HEX); // print as an


ASCII-encoded hexadecimal
serial.print("\t");
// print a tab
character
serial.print(analogValue, OCT); // print as an
ASCII-encoded octal
serial.print("\t");
// print a tab
character
serial.print(analogValue, BIN); // print as an
ASCII-encoded binary
serial.print("\t");
// print a tab
character
serial.print(analogValue/4, BYTE); // print as a
raw byte value (divide the
// value by 4 because
analogRead() returns numbers
// from 0 to 1023, but a
byte can only hold values
// up to 255)
serial.print("\t");
// print a tab
character
serial.println();
// print a linefeed
character
// delay 10 milliseconds before the next
reading:
delay(10);
}

SoftwareSerial: println(data)
Description
Prints data to the transmit pin of the
software serial port, followed by a
carriage return and line feed. Works the
same as the Serial.println() function.
Parameters
vary, see Serial.println() for details
Returns
byte
println() will return the number of bytes
written, though reading that number is
optional
Example
SoftwareSerial serial(10,11);
int analogValue;
void setup()
{
serial.begin(9600);
}
void loop()
{
// read the analog input on pin 0:
analogValue = analogRead(A0);
// print it out in many formats:
serial.print(analogValue);
// print as an

ASCII-encoded decimal
serial.print("\t");
// print a tab
character
serial.print(analogValue, DEC); // print as an
ASCII-encoded decimal
serial.print("\t");
// print a tab
character
serial.print(analogValue, HEX); // print as an
ASCII-encoded hexadecimal
serial.print("\t");
// print a tab
character
serial.print(analogValue, OCT); // print as an
ASCII-encoded octal
serial.print("\t");
// print a tab
character
serial.print(analogValue, BIN); // print as an
ASCII-encoded binary
serial.print("\t");
// print a tab
character
serial.print(analogValue/4, BYTE); // print as a
raw byte value (divide the
// value by 4 because
analogRead() returns numbers
// from 0 to 1023, but a
byte can only hold values
// up to 255)
serial.print("\t");
// print a tab
character
serial.println();
// print a linefeed
character
// delay 10 milliseconds before the next
reading:
delay(10);
}

SoftwareSerial: listen()
Description
Enables the selected software serial
port to listen. Only one software serial
port can listen at a time; data that
arrives for other ports will be discarded.
Any data already received is discarded
during the call to listen() (unless the
given instance is already listening).
Syntax
mySerial.listen()
Parameters
mySerial:the name of the instance to
listen
Returns
None
Example

SoftwareSerial portOne(10, 11);


// software serial : TX = digital pin 8, RX = digital
pin 9
SoftwareSerial portTwo(8, 9);
void setup()
{
// Start the hardware serial port
Serial.begin(9600);
// Start both software serial ports
portOne.begin(9600);
portTwo.begin(9600);
}
void loop()
{
portOne.listen();
if (portOne.isListening()) {
Serial.println("Port One is listening!");
}else{
Serial.println("Port One is not listening!");
}
if (portTwo.isListening()) {
Serial.println("Port Two is listening!");
}else{
Serial.println("Port Two is not listening!");
}
}

SoftwareSerial: write(data)
Description
Prints data to the transmit pin of the
software serial port as raw bytes.
Works the same as the Serial.write()
function.
Parameters
Serial.write() for details
Returns
byte
write() will return the number of bytes
written, though reading that number is
optional
Example
SoftwareSerial mySerial(10, 11);

#include <SoftwareSerial.h>

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

// software serial : TX = digital pin 10, RX =


digital pin 11

void loop()
{

mySerial.write(45); // send a byte with the value


45
int bytesSent = mySerial.write(hello); //send
the string hello and return the length of the
string.
}

Stepper Library

This library allows you to control


unipolar or bipolar stepper motors. To
use it you will need a stepper motor,
and the appropriate hardware to control
it. For more on that, see Tom Igoe's
notes on steppers.
Circuits
Unipolar Steppers
Bipolar Steppers
Functions
Stepper(steps, pin1, pin2)
Stepper(steps, pin1, pin2, pin3, pin4)
setSpeed(rpm)
step(steps)

Circuits for Unipolar Stepper


Motors

Two Pins

Four Pins

Circuit for Bipolar Stepper


Motor
Two Pins

Four Pins

Stepper(steps, pin1, pin2)


Stepper(steps, pin1, pin2,
pin3, pin4)
Description
This function creates a new instance of
the Stepper class that represents a
particular stepper motor attached to
your Arduino board. Use it at the top of
your sketch, above setup() and loop().
The number of parameters depends on
how you've wired your motor - either
using two or four pins of the Arduino
board.
Parameters
steps: the number of steps in one
revolution of your motor. If your motor
gives the number of degrees per step,
divide that number into 360 to get the
number of steps (e.g. 360 / 3.6 gives
100 steps). (int)
pin1, pin2: two pins that are attached to
the motor (int)
pin3, pin4: optional the last two pins
attached to the motor, if it's connected
to four pins (int)

Returns
A new instance of the Stepper motor
class.
Example
Stepper myStepper = Stepper(100, 5,
6);

Stepper: setSpeed(rpms)
Description
Sets the motor speed in rotations per
minute (RPMs). This function doesn't
make the motor turn, just sets the
speed at which it will when you call
step().
Parameters
rpms: the speed at which the motor
should turn in rotations per minute - a
positive number (long)
Returns
None
Stepper Motor Knob
Stepper motors, due to their unique
design, can be controlled to a high
degree of accuracy without any
feedback mechanisms. The shaft of a
stepper, mounted with a series of
magnets, is controlled by a series of
electromagnetic coils that are charged
positively and negatively in a specific
sequence, precisely moving it forward
or backward in small "steps".
There are two types of steppers,
Unipolars and Bipolars, and it is very
important to know which type you are
working with. For each of the motors,
there is a different circuit. The example
code will control both kinds of motors.
See theunipolar and bipolar motor
schematics for information on how to
wire up your motor.
In this example, a potentiometer (or
other sensor) on analog input 0 is used
to control the movement of a stepper
motor using the Arduino Stepper Library.
The stepper is controlled by with digital
pins 8, 9, 10, and 11 for either unipolar
or bipolar motors.
The Arduino will connect to a U2004
Darlington Array if you're using a unipolar

stepper or a SN754410NE H-Bridge if you


have a bipolar motor.
For more information about the
differences of the two types, please
take a look at Tom Igoe's page on stepper
motors.
Hardware Required
Arduino Board
potentiometer
stepper motor
U2004 Darlington Array (if using a
unipolar stepper)
SN754410ne H-Bridge (if using a
bipolar stepper)
power supply appropriate for your
particular stepper
breadboard
hookup wire
Circuits
Below you'll find circuits for both
unipolar and bipolar steppers. In either
case, it is best to power your stepper
motors from an external supply, as they
draw too much to be powered directly
from your Arduino board.
In both circuits, connect a 10k pot to
power and ground, with it's wiper
outputting to analog pin 0.
Note: Both circuits below are four wire
configurations. Two wire configurations
will not work with the code provided.
Unipolar Stepper Circuit and schematic

Show images for the unipolar circuit and


schematic

Bipolar Stepper Circuit and


schematic
Show images for the bipolar circuit and
schematic

Code
For both unipolar and bipolar steppers
/*
* MotorKnob
*
* A stepper motor follows the turns of a
potentiometer
* (or other sensor) on analog input 0.
*
* http://www.arduino.cc/en/Reference/Stepper
* This example code is in the public domain.
*/
#include <Stepper.h>

// change this to the number of steps on your


motor
#define STEPS 100
// create an instance of the stepper class,
specifying
// the number of steps of the motor and the pins
it's
// attached to
Stepper stepper(STEPS, 8, 9, 10, 11);
// the previous reading from the analog input
int previous = 0;
void setup()
{
// set the speed of the motor to 30 RPMs
stepper.setSpeed(30);
}
void loop()
{
// get the sensor value
int val = analogRead(0);
// move a number of steps equal to the change
in the
// sensor reading
stepper.step(val - previous);
// remember the previous value of the sensor
previous = val;
}

TFT LCD library


The TFT library is included with Arduino IDE
1.0.5 and later.
This library enables an Arduino board to
communicate with the Arduino TFT LCD
screen. It simplifies the process for drawing
shapes, lines, images, and text to the
screen.
The Arduino TFT library extends the Adafruit
GFX, and Adafruit ST7735 libraries that it is
based on. The GFX library is responsible for
the drawing routines, while
the ST7735library is specific to the screen
on the Arduino TFT. The Arduino specific
additions were designed to work as similarly
to the Processing API as possible.
Onboard the screen is a SD card slot, which
can be used through the SD library.
The TFT library relies on the SPI library for
communication with the screen and SD
card, and needs to be included in all
sketches.

Using the library


The screen can be configured for use in two
ways. One is to use an Arduino's hardware

SPI interface. The other is to declare all the


pins manually. There is no difference in the
functionality of the screen between the two
methods, but using hardware SPI is
significantly faster.
If you plan on using the SD card on the TFT
module, you must use hardware SPI. All
examples in the library are written for
hardware SPI use.
If using hardware SPI with the Uno, you only
need to declare the CS, DC, and RESET
pins, as MOSI (pin 11) and SCLK (pin 13)
are already defined.
#define CS 10
#define DC 9
#define RESET 8
TFT myScreen = TFT(CS, DC, RESET);
[Get Code]

To use hardware SPI with the Leonardo,


you declare the pins like so :
#define CS 7
#define DC 0
#define RESET 1
TFT myScreen = TFT(CS, DC, RESET);
[Get Code]

When not using hardware SPI, you can use


any available pins, but you must declare the
MOSI and SCLK pins in addition to CD, DC,
and RESET.
#define SCLK 4
#define MOSI 5
#define CS 6
#define DC 7
#define RESET 8
TFT
myScreen = TFT(CS, DC, MOSI, SCLK, RESET
);
[Get Code]

Using the Arduino Esplora and the TFT


library
As the Arduino Esplora has a socket
designed for the TFT, and the pins for using
the screen are fixed, an Esplora only object
is created when targeting sketches for that
board. You can reference the screen
attached to an Esplora through EsploraTFT.

Similarities to Processing
Processing is an open source software
environment used by designers, artists, and
students. The main output of Processing is a
graphic window on a computer or browser.
The Arduino TFT library has made the calls
for drawing primitives and text to the screen
as "Processing-like" as possible to ensure a
smooth transition between the two

environments.
Examples

There are two groups of examples for the


TFT. There are examples specific to the
Arduino Esplora, and examples that are
designed for boards like the Uno or
Leonardo. It should be easy to translate
from one to the other once you've gotten a
handle on the library and its functionality.
Esplora
Esplora TFT Bitmap Logo: Read an image file

from a micro-SD card and draw it at random


locations.
Esplora TFT Color Picker: Using the joystick and
slider, change the color of the TFT screen
Esplora TFT Etch a Sketch: An Esplora
implementation of the classic Etch-a-Sketch
Esplora TFT Graph: Graph the values from the
light sensor to the TFT
Esplora TFT Horizon: Draw an artificial horizon
line based on the tilt from the accelerometer
Esplora TFT Pong: A basic implementation of
the classic game
Esplora TFT Temperature: Check the
temperature with the onboard sensor and
display it on screen

Parameters
cs : int, pin for chip select
dc : int, pin used for
rst : int, pin used for reset
mosi : int, pin used for MOSI
communication when not using
hardware SPI
sclk : int, pin used for the shared clock,
when not using hardware SPI
Returns
none
Example
#include <SPI.h>
#include <TFT.h>
#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);
void setup() {
// initialize the screen
screen.begin();

Arduino

// make the background black


screen.background(0,0,0);

TFT Bitmap Logo: Read an image file from a

micro-SD card and draw it at random locations.


TFT Display Text : Read the value of a sensor

and print it on the screen.


TFT Pong: An Arduino implementation of the
classic game
Etch a Sketch: An Arduino version of the classic
Etch-a-Sketch
Color Picker: With three sensors, change the
color of the TFT screen
Graph: Graph the values from a variable resistor
to the TFT

For additional information on the TFT


screen, see the Getting Started page and
thehardware page.

TFT

Description
The base class for drawing to the
Arduino TFT screen. Use this to create
an named instance of the TFT class to
refer to in your sketch.
if using the Arduino Explora, you do not
need to call this, all references to the
screen are handled
through EsploraTFT.
Syntax
TFT(cs, dc, rst); for using hardware SPI
TFT(cs, dc, mosi, sclk, rst); for use on
any pins

// Arduino LCD library

// set the stroke color to white


screen.stroke(255,255,255);
// turn off fill coloring
screen.noFill();
// draw a rectangle in the center of screen
screen.line(screen.width()/25, screen.height()/2-5, 10, 10);
}
void loop() {
}

EsploraTFT
Description
This is the named instance of the TFT
class when targeting the Arduino
Esplora board.
Syntax
EsploraTFT
Parameters
none
Returns
none

Example
#include <Esplora.h>
#include <SPI.h>
#include <TFT.h>

// Arduino LCD library

void setup() {
// initialize the screen
EsploraTFT.begin();
// make the background white
EsploraTFT.background(255,255,255);
}

void loop() {
}

#include <SPI.h>
#include <TFT.h>

begin
Description
Must be called to initialize the Arduino
GLCD screen before drawing anything.
Syntax
screen.begin()
Parameters
none
Returns
none
Example
#include <SPI.h>
#include <TFT.h>

blue channels, the screen does not


display with this fidelity. The red and
blue values are scaled to 5-bit color (32
discrete steps), and the green is 6-bit
color (64 discrete steps).
Syntax
screen.background(red, green, blue);
Parameters
red : int 0-255
green : int 0-255
blue : int 0-255
Returns
none
Example
// Arduino LCD library

#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);
void setup() {
// initialize the screen
screen.begin();
// make the background white
screen.background(255,255,255);

// Arduino LCD library

#define cs 10
#define dc 9
#define rst 8

void loop() {

TFT screen = TFT(cs, dc, rst);

stroke

void setup() {
// initialize the screen
screen.begin();

Description
Called before drawing an object on
screen, it sets the color of lines and
borders around shapes.
stroke() expects 8-bit values for each of
the red, green, and blue channels, but
the screen does not display with this
fidelity. The red and blue values are
scaled to 5-bit color (32 discrete steps),
and the green is 6-bit color (64 discrete
steps).
Syntax
screen.stroke(red, green, blue);
Parameters
red : int 0-255
green : int 0-255
blue : int 0-255

// make the background white


screen.background(255,255,255);
}
void loop() {
}

background
Description
Erases everything currently on the LCD
screen with the indicated color. Can be
used in loop() to clear the screen.
While background() expects 8-bit
values for each of the red, green, and

#define cs 10
#define dc 9
#define rst 8

Returns
none
Example
#include <SPI.h>
#include <TFT.h>

// Arduino LCD library

void setup() {
// initialize the screen
screen.begin();

#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);

// make the background black


screen.background(0,0,0);

void setup() {
// initialize the screen
screen.begin();

// set the stroke color to white


screen.stroke(255,255,255);

// make the background black


screen.background(0,0,0);
// set the stroke color to white
screen.stroke(255,255,255);
// draw a box with a white outline in the middle
of the screen
screen.rect(screen.width()/2+10,screen.height(
)/2+10,screen.width()/2-10,screen.height()/2-10);
}
void loop() {
}

stroke

TFT screen = TFT(cs, dc, rst);

Description
Called before drawing an object on
screen, it sets the color of lines and
borders around shapes.
stroke() expects 8-bit values for each of
the red, green, and blue channels, but
the screen does not display with this
fidelity. The red and blue values are
scaled to 5-bit color (32 discrete steps),
and the green is 6-bit color (64 discrete
steps).
Syntax
screen.stroke(red, green, blue);
Parameters
red : int 0-255
green : int 0-255
blue : int 0-255
Returns
none
Example
#include <SPI.h>
#include <TFT.h>

// Arduino LCD library

// draw a box with a white outline in the middle


of the screen
screen.rect(screen.width()/2+10,screen.height(
)/2+10,screen.width()/2-10,screen.height()/2-10);
}
void loop() {
}

noStroke
Description
After calling this, any shapes drawn on
screen will not have an outline stroke
color.
Syntax
screen.noStroke();
Parameters
none
Returns
none
Example
#include <SPI.h>
#include <TFT.h>

// Arduino TFT library

#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);
void setup() {
// initialize the screen
screen.begin();
// make the background black
screen.background(0,0,0);
// turn the stroke off
screen.noStroke();
// set the fill color to white

screen.noFill(255,255,255);
// draw a rectangle in the center of screen
screen.line(screen.width()/25, screen.height()/2-5, 10, 10);
}

void loop() {
}

noFill
Description
After calling this, any shapes drawn on
screen will not be filled in.
Syntax
screen.noFill();
Parameters
none
Returns
none
Example
#include <SPI.h>
#include <TFT.h>

Syntax
screen.text(text, xPos, yPos);
Parameters
text : char array, the text you want to
write on the screen
xPos : int, the location on the x-axis
you want to start drawing text to the
screen
yPos : int, the location on the y-axis
you want to start drawing text to the
screen
Returns
none
Example
#include <SPI.h>
#include <TFT.h>
#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);

// Arduino TFT library

void setup() {
// initialize the screen
screen.begin();

#define cs 10
#define dc 9
#define rst 8

// make the background black


screen.background(0,0,0);

TFT screen = TFT(cs, dc, rst);

// set the text color to white


screen.stroke(255,255,255);

void setup() {
// initialize the screen
screen.begin();

// write text to the screen in the top left corner


screen.text("Testing!", 0, 0);

// make the background black


screen.background(0,0,0);

}
void loop() {

// turn the fill off


screen.noFill();

// set the stroke color to white


screen.stroke(255,255,255);

setTextSize

// draw a rectangle in the center of screen


screen.line(screen.width()/25, screen.height()/2-5, 10, 10);
}
void loop() {
}

text
Description
Write text to the screen at the given
coordinates.

// Arduino TFT library

Description
Sets the size of text that follows. The
default size is "1". Each change in size
increases the text by 10 pixels in
height. That is, size 1 = 10 pixels, size
2 =20 pixels, and so on.
Syntax
screen.setTextSize(size);
Parameters
size : int 1-5
Returns
none

// make the background white


screen.background(255,255,255);

Example
#include <SPI.h>
#include <TFT.h>

// Arduino TFT library

#define cs 10
#define dc 9
#define rst 8

void loop() {

TFT screen = TFT(cs, dc, rst);

point

void setup() {
// initialize the screen
screen.begin();
// make the background black
screen.background(0,0,0);
// set the stroke color to white
screen.fill(255,255,255);
// default text size
screen.setTextSize(1);
// write text to the screen in the top left corner
screen.text("Testing!", 0, 0);
// increase text size
screen.setTextSize(5);
// write text to the screen below
screen.text("BIG!", 0, 10);
}
void loop() {

begin
Description
Must be called to initialize the Arduino
GLCD screen before drawing anything.
Syntax
screen.begin()
Parameters
none
Returns
none
Example
// Arduino LCD library

#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);
void setup() {
// initialize the screen
screen.begin();

#include <SPI.h>
#include <TFT.h>

// Arduino TFT library

#define cs 10
#define dc 9
#define rst 8

#include <SPI.h>
#include <TFT.h>

Description
Draws a point at the given coordinates.
The first parameter is the horizontal
value for the point, the second value is
the vertical value for the point.
Syntax
screen.fill(xPos, yPos);
Parameters
xPos : int, the horizontal position of the
point
yPos : int, the vertical position of the
point
Returns
none
Example

TFT screen = TFT(cs, dc, rst);


void setup() {
// initialize the screen
screen.begin();
// make the background black
screen.background(0,0,0);
// set the stroke color to white
screen.fill(255,255,255);
// draw a pixel in the screen's center
screen.point(screen.width()/2, screen.height()/2
);
}
void loop() {
}

line

Description
Draws a line between two points.
Use stroke() to change the color of
something drawn with line().
Syntax
screen.line(xStart, yStart, xEnd, yEnd);
Parameters
xStart : int, the horizontal position
where the line starts
yStart : int, the vertical position where
the line starts
xEnd : int, the horizontal position where
the line ends
yEnd : int, the vertical position where
the line ends
Returns
none
Example
#include <SPI.h>
#include <TFT.h>

// Arduino TFT library

Parameters
xStart : int, the horizontal position
where the line starts
yStart : int, the vertical position where
the line starts
width : int, the width of the rectangle
height : int, the height of the rectangle
Returns
none
Example
#include <SPI.h>
#include <TFT.h>

// Arduino TFT library

#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);
void setup() {
// initialize the screen
screen.begin();

#define cs 10
#define dc 9
#define rst 8

// make the background black


screen.background(0,0,0);

TFT screen = TFT(cs, dc, rst);

// set the stroke color to white


screen.stroke(255,255,255);

void setup() {
// initialize the screen
screen.begin();

// set the fill color to grey


screen.fill(127,127,127);

// make the background black


screen.background(0,0,0);
// set the stroke color to white
screen.stroke(255,255,255);
// draw a diagonal line across the screen's
center
screen.line(0, 0, 160, 124);
}
void loop() {
}

rect
Description
Draws a rectangle to the TFT
screen. rect() takes 4 arguments, the
first two are the top left corner of the
shape, the last two are the width and
height of the shape.
Syntax
screen.rect(xStart, yStart, xEnd, yEnd);

// draw a rectangle in the center of screen


screen.line(screen.width()/25, screen.height()/2-5, 10, 10);
}
void loop() {
}

width
Description
Reports the width of the TFT screen in
pixels.
Syntax
screen.width();
Parameters
none
Returns
int : the width of the screen in pixels
Example
#include <SPI.h>
#include <TFT.h>
#define cs 10

// Arduino TFT library

#define dc 9
#define rst 8

// draw a rectangle in the center of screen


screen.line(screen.width()/25, screen.height()/2-5, 10, 10);
}

TFT screen = TFT(cs, dc, rst);


void setup() {
// initialize the screen
screen.begin();

void loop() {
}

// make the background black


screen.background(0,0,0);

circle

// set the stroke color to white


screen.stroke(255,255,255);
// set the fill color to grey
screen.fill(127,127,127);
// draw a rectangle in the center of screen
screen.line(screen.width()/25, screen.height()/2-5, 10, 10);
}

void loop() {

height
Description
Reports the height of the TFT screen in
pixels.
Syntax
screen.height();
Parameters
none
Returns
int : the height of the screen in pixels
Example
#include <SPI.h>
#include <TFT.h>

// Arduino TFT library

Description
Draws a circle on the screen.
The circle is drawn relative to its center
point, which means the total diameter
will always be an odd number.
Syntax
screen.circle(xPos, yPos, radius);
Parameters
xPos : int, the location of the center of
the circle on the x axis
yPos : int, the location of the center of
the circle on the y axis
radius : int, the radius of the circle
Returns
int : the width of the screen in pixels
Example
#include <SPI.h>
#include <TFT.h>

// Arduino TFT library

#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);
void setup() {
// initialize the screen
screen.begin();

#define cs 10
#define dc 9
#define rst 8

// make the background black


screen.background(0,0,0);

TFT screen = TFT(cs, dc, rst);

// set the stroke color to white


screen.stroke(255,255,255);

void setup() {
// initialize the screen
screen.begin();

// set the fill color to grey


screen.fill(127,127,127);

// make the background black


screen.background(0,0,0);
// set the stroke color to white
screen.stroke(255,255,255);
// set the fill color to grey
screen.fill(127,127,127);

// draw a circle in the center of screen


screen.circle(screen.width()/2, screen.height()/
2, 10);
}
void loop() {
}

image

Description
Draws an image from the SD card to
the screen at a specified location.
Syntax
screen.image(image, xPos, yPos);
Parameters
image : a named instance of PImage.
xPos : int, location on the x-axis to start
drawing
yPos : int, location on the y-axis to start
drawing
Returns
none
Example

loadImage

// this example looks for a file named "logo.bmp"


// on the SD card, and renders it to the screen
#include <Esplora.h>
#include <SPI.h>
#include <SD.h>
#include <TFT.h>
// Arduino TFT library
#define SD_CS
card in Esplora

8 // Chip select line for SD

PImage logo;
void setup() {
// initialize the screen
EsploraTFT.begin();
// initialize the SD card
SD.begin(SD_CS);
// set the background the black
EsploraTFT.background(0, 0, 0);
// load the image into the named instance of
PImage
logo = EsploraTFT.loadImage("arduino.bmp");
// if it is a valid image file, turn the Esplora's
LED green
if (logo.isValid()) {
Esplora.writeGreen(255);
}
else{
// if it is not valid, turn the LED red
Esplora.writeRed(255);
}
// draw the image on the screen starting at the
top left corner
EsploraTFT.image(logo, 0, 0);
}
void loop() {

Description
Loads an image file from the SD card
into a named instance of PImage.
Syntax
screen.loadImage(name);
Parameters
name : char array, the name of the
image from the SD card you wish to
read
Returns
none
Example
// this example looks for a file named "logo.bmp"
// on the SD card, and renders it to the screen
#include <Esplora.h>
#include <SD.h>
#include <SPI.h>
#include <TFT.h>
// Arduino TFT library
#define SD_CS
card in Esplora

8 // Chip select line for SD

PImage logo;
void setup() {
// initialize the screen
EsploraTFT.begin();
// initialize the SD card
SD.begin(SD_CS);
// set the background the black
EsploraTFT.background(0, 0, 0);
// load the image into the named instance of
PImage
logo = EsploraTFT.loadImage("arduino.bmp");
// if it is a valid image file, turn the Esplora's
LED green
if (logo.isValid()) {
Esplora.writeGreen(255);
}
else{
// if it is not valid, turn the LED red
Esplora.writeRed(255);
}
// draw the image on the screen starting at the
top left corner
EsploraTFT.image(logo, 0, 0);
}
void loop() {

void loop() {
}
}

PImage
Description
The base class for drawing a bitmap
image from the SD card onscreen. You
must include the SD library to
use PImage.
Syntax
PImage image;
Parameters
image : the name of the PImage object.
You'll refer to this when drawing
images on screen.
Returns
none
Example
// this example looks for a file named "logo.bmp"
// on the SD card, and renders it to the screen
#include <Esplora.h>
#include <SD.h>
#include <SPI.h>
#include <TFT.h>
// Arduino TFT library
#define SD_CS
card in Esplora

8 // Chip select line for SD

PImage logo;
void setup() {
// initialize the screen
EsploraTFT.begin();
// initialize the SD card
SD.begin(SD_CS);
// set the background the black
EsploraTFT.background(0, 0, 0);
// load the image into the named instance of
PImage
logo = EsploraTFT.loadImage("arduino.bmp");
// if it is a valid image file, turn the Esplora's
LED green
if (logo.isValid()) {
Esplora.writeGreen(255);
}
else{
// if it is not valid, turn the LED red
Esplora.writeRed(255);
}
// draw the image on the screen starting at the
top left corner
EsploraTFT.image(logo, 0, 0);
}

PImage.height
Description
Checks the height of
the PImage object.
Syntax
image.height();
Parameters
none
Returns
int : the image's height in pixels
Example
// this example looks for a file named "logo.bmp"
// on the SD card, and renders it to the screen
#include <Esplora.h>
#include <SD.h>
#include <SPI.h>
#include <TFT.h>
// Arduino TFT library
#define SD_CS
card in Esplora

8 // Chip select line for SD

PImage logo;
void setup() {
// initialize the screen
EsploraTFT.begin();
// initialize the SD card
SD.begin(SD_CS);
// set the background the black
EsploraTFT.background(0, 0, 0);
// load the image into the named instance of
PImage
logo = EsploraTFT.loadImage("arduino.bmp");
// if it is a valid image file, turn the Esplora's
LED green
if (logo.isValid()) {
Esplora.writeGreen(255);
}
else{
// if it is not valid, turn the LED red
Esplora.writeRed(255);
}
}
void loop() {
// randomly draw the image on screen
int x = random(EsploraTFT.width() logo.width());
int y = random(EsploraTFT.height() logo.height());
EsploraTFT.image(logo, x, y);

delay(1500);
}
}

PImage.width
Description
Checks the width of the PImage object.
Syntax
image.width();
Parameters
none
Returns
int : the image's width in pixels
Example
// this example looks for a file named "logo.bmp"
// on the SD card, and renders it to the screen
#include <Esplora.h>
#include <SD.h>
#include <SPI.h>
#include <TFT.h>
// Arduino TFT library
#define SD_CS
card in Esplora

8 // Chip select line for SD

PImage logo;
void setup() {
// initialize the screen
EsploraTFT.begin();
// initialize the SD card
SD.begin(SD_CS);
// set the background the black
EsploraTFT.background(0, 0, 0);
// load the image into the named instance of
PImage
logo = EsploraTFT.loadImage("arduino.bmp");
// if it is a valid image file, turn the Esplora's
LED green
if (logo.isValid()) {
Esplora.writeGreen(255);
}
else{
// if it is not valid, turn the LED red
Esplora.writeRed(255);
}
}
void loop() {
// randomly draw the image on screen
int x = random(EsploraTFT.width() logo.width());
int y = random(EsploraTFT.height() logo.height());
EsploraTFT.image(logo, x, y);
delay(1500);

PImage.isValid
Description
Checks if a named instance
of PImage references a valid bitmap
file.
Syntax
image.isValid();
Parameters
none
Returns
boolean
Example
// this example looks for a file named "logo.bmp"
// on the SD card, and renders it to the screen
#include <Esplora.h>
#include <SD.h>
#include <SPI.h>
#include <TFT.h>
// Arduino TFT library
#define SD_CS
card in Esplora

8 // Chip select line for SD

PImage logo;
void setup() {
// initialize the screen
EsploraTFT.begin();
// initialize the SD card
SD.begin(SD_CS);
// set the background the black
EsploraTFT.background(0, 0, 0);
// load the image into the named instance of
PImage
logo = EsploraTFT.loadImage("arduino.bmp");
// if it is a valid image file, turn the Esplora's
LED green
if (logo.isValid()) {
Esplora.writeGreen(255);
}
else{
// if it is not valid, turn the LED red
Esplora.writeRed(255);
}
// draw the image on the screen starting at the
top left corner
EsploraTFT.image(logo, 0, 0);
}
void loop() {
}

TFT Bitmap Logo

using different pins. see the getting


started page for more details.
Show me how to do that
Code
To use the screen you must first
include the SPI and TFT libraries. You
also need to include the SD library to
read the image from the card.
#include <SD.h>
#include <SPI.h>
#include <TFT.h>
[Get Code]

This example for the Arduino TFT


screen reads a bitmap file from a SD
card and displays it on screen in a
random location.
For this example to work, you need to
save an image named "logo.bmp" to
the root of the SD card. The SD card
needs to
be FAT16 and FAT32 formatted. See
the SD library documentation for more
information on working with SD cards.
Hardware Required
Arduino Uno
Arduino TFT screen
micro-SD card
image file
Circuit
Insert the SD card with the "logo.bmp"
file into the SD card slot on the back of
your screen.
Connect power and ground to the
breadboard.
Show me how to do that
Connect the screen to the breadboard.
The headers on the side of the screen
with the small blue tab and arrow
should be the ones that attach to the
board. Pay attention to the orientation
of the screen, in these images, it is
upside down.
Show me how to do that
Connect the BL and +5V pins to power,
and GND to ground. Connect CS-LD to
pin 10, DC to pin 9, RESET to pin 8,
MOSI to pin 11, and SCK to pin 13. If
uyou're using a Leonardo, you'll be

Define the pins you're going to use for


controlling the screen, and a pin for the
SD chip select. Create an instance of
the TFT library named TFTscreen.
#define sd_cs 4
#define lcd_cs 10
#define dc 9
#define rst 8
TFT TFTscreen = TFT(cs, dc, rst);
[Get Code]

There is a special datatype


called PImage for holding image
information. Create a named version
of PImage
PImage logo;
[Get Code]

In setup(), you're going to initialize the


serial port and wait for it to become
active before starting up. If you want to
ignore the status information, comment
out the while() loop.
Once serial communication has started,
initialize the SD library. If there is an
error, send a message to the serial
monitor.
void setup() {
Serial.begin(9600);
while (!Serial) {
}
Serial.print("Initializing SD card...");
if (!SD.begin(SD_CS)) {
Serial.println("failed!");
return;
}
Serial.println("OK!");
[Get Code]

Initialize and clear the screen


TFTscreen.begin();
TFTscreen.background(255, 255, 255);
[Get Code]

Read the image file into


the PImage you named earlier
with loadimage(). loadImage() prints out some
useful information about the image to
the serial monitor.
logo = TFTscreen.loadImage("logo.bmp");
if (!logo.isValid()) {
Serial.println("error while loading
arduino.bmp");
}
}
[Get Code]

If the image wasn't loaded correctly,


stop the sketch before going any
further.
void loop() {
if (logo.isValid() == false) {
return;
}
[Get Code]

If the image information is valid, pick a


random spot on the screen to display
the image. To make sure all the image
is drawn onscreen, take the dimensions
of the image and subtract that from the
screen's dimensions.
int x = random(TFTscreen.width() - logo.width());
int y = random(TFTscreen.height() logo.height());
[Get Code]

Draw the image onscreen starting at


the random coordinates from the
previous step, and wait for a little bit
before entering the next loop()
TFTscreen.image(logo, x, y);
delay(1500);
}
[Get Code]

The complete sketch is below :


/*
Arduino TFT Bitmap Logo example
This example reads an image file from a microSD card
and draws it on the screen, at random locations.
In this sketch, the Arduino logo is read from a
micro-SD card.
There is a .bmp file included with this sketch.
- open the sketch folder (Ctrl-K or Cmd-K)
- copy the "arduino.bmp" file to a micro-SD
- put the SD into the SD slot of the Arduino TFT
module.
This example code is in the public domain.

Created 19 April 2013 by Enrico Gueli


http://arduino.cc/en/Tutorial/TFTBitmapLogo
*/
// include the necessary libraries
#include <SPI.h>
#include <SD.h>
#include <TFT.h> // Arduino LCD library
// pin definition for the Uno
#define sd_cs 4
#define lcd_cs 10
#define dc 9
#define rst 8
// pin definition for the Leonardo
//#define sd_cs 8
//#define lcd_cs 7
//#define dc 0
//#define rst 1
TFT TFTscreen = TFT(lcd_cs, dc, rst);
// this variable represents the image to be drawn
on screen
PImage logo;
void setup() {
// initialize the GLCD and show a message
// asking the user to open the serial line
TFTscreen.begin();
TFTscreen.background(255, 255, 255);
TFTscreen.stroke(0, 0, 255);
TFTscreen.println();
TFTscreen.println("Arduino TFT Bitmap
Example");
TFTscreen.stroke(0, 0, 0);
TFTscreen.println("Open serial monitor");
TFTscreen.println("to run the sketch");
// initialize the serial port: it will be used to
// print some diagnostic info
Serial.begin(9600);
while (!Serial) {
// wait for serial line to be ready
}
// clear the GLCD screen before starting
TFTscreen.background(255, 255, 255);
// try to access the SD card. If that fails (e.g.
// no card present), the setup process will stop.
Serial.print("Initializing SD card...");
if (!SD.begin(sd_cs)) {
Serial.println("failed!");
return;
}

Serial.println("OK!");
// initialize and clear the GLCD screen
TFTscreen.begin();
TFTscreen.background(255, 255, 255);
// now that the SD card can be access, try to
load the
// image file.
logo = TFTscreen.loadImage("arduino.bmp");
if (!logo.isValid()) {
Serial.println("error while loading
arduino.bmp");
}
}
void loop() {
// don't do anything if the image wasn't loaded
correctly.
if (logo.isValid() == false) {
return;
}
Serial.println("drawing image");
// get a random location where to draw the
image.
// To avoid the image to be draw outside the
screen,
// take into account the image size.
int x = random(TFTscreen.width() logo.width());
int y = random(TFTscreen.height() logo.height());
// draw the image to the screen
TFTscreen.image(logo, x, y);
// wait a little bit before drawing again
delay(1500);
}

TFT Display Text

Arduino reads the value of an analog


sensor attached to pin A0, and writes
the value to the LCD screen, updating
every quarter second.
Hardware Required
Arduino Uno
Arduino TFT screen
breadboard
hookup wire
one 10-kilohm potentiometer
Circuit
Connect power and ground to the
breadboard.
Show me how to do that
Place the potentiometer on the
breadboard. Connect one side to
ground, and the other to power.
Connect the middle pin to A0.
Show me how to do that
Connect the screen to the breadboard.
The headers on the side of the screen
with the small blue tab and arrow
should be the ones that attach to the
board. Pay attention to the orientation
of the screen, in these images, it is
upside down.
Show me how to do that
Connect the BL and +5V pins to power,
and GND to ground. Connect CS-LD to
pin 10, DC to pin 9, RESET to pin 8,
MOSI to pin 13, and SCK to pin 11. If
you're using a Leonardo, you'll be using
different pins. see the getting started
page for more details.
Show me how to do that
Code
To use the screen you must first
include the SPI and TFT libraries.
#include <SPI.h>
#include <TFT.h>
[Get Code]

Define the pins you're going to use for


controlling the screen, and create an
instance of the TFT library
namedTFTscreen. You'll reference that
object whenever you're working with
the screen.
This example demonstrates how to
draw text on the Arduino GLCD screen
when connected to an Arduino. The

#define cs 10
#define dc 9
#define rst 8
TFT TFTscreen = TFT(cs, dc, rst);

[Get Code]

To update the screen with text, you'll


need to store dynamic content in a char
array.
char sensorPrintout[4];

In setup(), initialize the screen and clear


the background. Set the color for the
font with stroke(), and write any static text
to the screen. In this case, you'll write
"Sensor Value :". This will stay at the
top of the screen and not change as
long as the sketch runs. Before
entering the loop(), set the text size so
you can really see the sensor values
stand out.
void setup() {
TFTscreen.begin();

The complete sketch is below :


/*
Arduino TFT text example
This example demonstrates how to draw text
on the
TFT with an Arduino. The Arduino reads the
value
of an analog sensor attached to pin A0, and
writes
the value to the LCD screen, updating every
quarter second.
This example code is in the public domain
Created 15 April 2013 by Scott Fitzgerald
http://arduino.cc/en/Tutorial/TFTDisplayText
*/

TFTscreen.background(0, 0, 0);
TFTscreen.stroke(255,255,255);
TFTscreen.setTextSize(2);
TFTscreen.text("Sensor Value : ",0,0);
TFTscreen.setTextSize(5);
}
[Get Code]

In loop(), read the value from the


potentiometer and store it in a string.
Convert the string content to a char
array, storing it in the global array you
declared int he beginning of your
program.

#include <TFT.h> // Arduino LCD library


#include <SPI.h>
// pin definition for the Uno
#define cs 10
#define dc 9
#define rst 8
// pin definition for the Leonardo
// #define cs 7
// #define dc 0
// #define rst 1
// create an instance of the library
TFT TFTscreen = TFT(cs, dc, rst);

void loop() {
String sensorVal = String(analogRead(A0));
sensorVal.toCharArray(sensorPrintout, 4);
[Get Code]

Set the text color (this would be a good


place to change the color of the text
depending on the value from the
potentiometer), and print it to the
screen below the static text.
TFTscreen.stroke(255,255,255);
TFTscreen.text(sensorPrintout, 0, 20);
[Get Code]

Wait a wuarter second second, then


erase the text you just wrote, so you
can update it in the next run
through loop().
delay(250);
TFTscreen.stroke(0,0,0);
TFTscreen.text(sensorPrintout, 0, 20);
}
[Get Code]

// char array to print to the screen


char sensorPrintout[4];
void setup() {
// Put this line at the beginning of every sketch
that uses the GLCD:
TFTscreen.begin();
// clear the screen with a black background
TFTscreen.background(0, 0, 0);
// write the static text to the screen
// set the font color to white
TFTscreen.stroke(255,255,255);
// set the font size
TFTscreen.setTextSize(2);
// write the text to the top left corner of the
screen
TFTscreen.text("Sensor Value :\n ",0,0);
// ste the font size very large for the loop
TFTscreen.setTextSize(5);
}

void loop() {
// Read the value of the sensor on A0
String sensorVal = String(analogRead(A0));
// convert the reading to a char array
sensorVal.toCharArray(sensorPrintout, 4);
// set the font color
TFTscreen.stroke(255,255,255);
// print the sensor value
TFTscreen.text(sensorPrintout, 0, 20);
// wait for a moment
delay(250);
// erase the text you just wrote
TFTscreen.stroke(0,0,0);
TFTscreen.text(sensorPrintout, 0, 20);
}

TFT Pong

This sketch is a basic implementation


of pong for the TFT screen with an
Arduino Uno.
This version of the game creates a
rectangular platform that can move in
two directions, and a ball that bounces
against the edges of the screen as well
as the movable platform. Two
potentiometers (or other analog sensor)
control the position of the platform.
The example demonstrates collision
detection between objects on the
screen, as well as how to quickly
update images without erasing the
entire screen every loop()
Hardware Required
Arduino Uno
Arduino TFT screen
breadboard
hookup wire
two 10-kilohm potentiometers
Circuit

Connect power and ground to the


breadboard.
Show the circuit
Place the potentiometers on the
breadboard. On each pot, connect one
side to ground, and the other to power.
Connect the middle pin of one
potentiometer to A0, the other one to
A1.
Show the circuit
Connect the TFT screen to the
breadboard. The headers on the side of
the screen with the small blue tab and
arrow should be the ones that attach to
the board. Pay attention to the
orientation of the screen, in these
images, it is upside down.
Show the circuit
Connect the BL and +5V pins to power,
and GND to ground. Connect CS-LD to
pin 10, DC to pin 9, RESET to pin 8,
MOSI to pin 13, and SCK to pin 11. If
uyou're using a Leonardo, you'll be
using different pins. see the getting
started page for more details.
Show the circuit
Code
To use the screen you must first
include the SPI and TFT libraries.
#include <SPI.h>
#include <TFT.h>
[Get Code]

Define the pins you're going to use for


controlling the screen, and create an
instance of the TFT library
namedTFTscreen. You'll reference that
object whenever you're working with
the screen.
#define cs 10
#define dc 9
#define rst 8
TFT TFTscreen = TFT(cs, dc, rst);
[Get Code]

Set up the variables for the ball and


paddle x & y positions, the ball's
direction, and the previous locations of
the ball and paddle.
int paddleX = 0;
int paddleY = 0;
int oldPaddleX, oldPaddleY;
int ballDirectionX = 1;
int ballDirectionY = 1;

int ballX, ballY, oldBallX, oldBallY;


[Get Code]

In setup(), initialize the display and clear


the screen's background.
void setup() {
TFTscreen.begin();
TFTscreen.background(0,0,0);
}
[Get Code]

starts by storing the width and


height of the screen, an reading the
values of the potentiometers, before
mapping them to a useful range.
loop()

void loop() {
int myWidth = TFTscreen.width();
int myHeight = TFTscreen.height();
paddleX = map(analogRead(A0), 512, 512, 0, myWidth) - 20/2;
paddleY = map(analogRead(A1), 512, 512, 0, myHeight) - 5/2;
[Get Code]

Set the fill color to black, and erase the


previous location of the paddle if it has
moved.

if (millis() % ballSpeed < 2) {


moveBall();
}
}
[Get Code]

will update the ball's position,


erase its previous location, and draw it
in the new spot. It will also check to
make sure it does not go off the screen,
reversing direction when it hits the
sides. This also calls a second custom
function named inPaddle() which checks
for intersections of the ball and paddle.
moveBall()

void moveBall() {
if (ballX > TFTscreen.width() || ballX < 0) {
ballDirectionX = -ballDirectionX;
}
if (ballY > TFTscreen.height() || ballY < 0) {
ballDirectionY = -ballDirectionY;
}
if (inPaddle(ballX, ballY, paddleX, paddleY, 20,
5)) {
ballDirectionY = -ballDirectionY;
}
ballX += ballDirectionX;
ballY += ballDirectionY;

TFTscreen.fill(0,0,0);

TFTscreen.fill(0,0,0);

if (oldPaddleX != paddleX || oldPaddleY != pad


dleY) {
TFTscreen.rect(oldPaddleX, oldPaddleY, 20,
5);
}
[Get Code]

if (oldBallX != ballX || oldBallY != ballY) {


TFTscreen.rect(oldBallX, oldBallY, 5, 5);
}

Set the fill color to white, and draw the


paddle.

TFTscreen.fill(255,255,255);
TFTscreen.rect(ballX, ballY, 5, 5);

TFTscreen.fill(255,255,255);
TFTscreen.rect(paddleX, paddleY, 20, 5);
[Get Code]

oldBallX = ballX;
oldBallY = ballY;

Save the paddle's current location as


the previous location, so the next time
through you can check if it has moved.
oldPaddleX = paddleX;
oldPaddleY = paddleY;
[Get Code]

At the end of loop(), use the value of


the ballSpeed variable to determine how
quickly the display will update. Once
you've finished with the example, you
could add another potentiometer and
change the speed dynamically by
changing the value of ballSpeed.
You'll call a custom function
named moveBall() to update the ball's
position.

}
[Get Code]

checks to see if the paddle and


ball occupy the same space. If so, it
returns TRUE, which reverses the ball's
direction in moveBall().
inPaddle()

boolean inPaddle(int x, int y, int rectX, int rectY, i


nt rectWidth, int rectHeight) {
boolean result = false;
if ((x >= rectX && x <= (rectX + rectWidth)) &&
(y >= rectY && y <= (rectY + rectHeight))) {
result = true;
}
return result;
}

TFT EtchASketch

This example for the Arduino TFT


draws a white line on the screen, based
on the position of 2 potentiometers. If
you press a momentary button, the
screen will erase.
Hardware Required
Arduino Uno
Arduino TFT screen
breadboard
hookup wire
two 10-kilohm potentiometers
momentary switch
10-kilohm resistor
Circuit
Connect power and ground to the
breadboard.
Show me how to do that
Place the potentiometers on the
breadboard. On each pot, connect one
side to ground, and the other to power.
Connect the middle pin of one
potentiometer to A0, the other one to
A1.
Show me how to do that
Put a switch across the center of the
breadboard. Connect one end to
power, the other end to the Arduino
digital pin 2. Connect the same pin to
ground through a 10-kilohm pull-down
resistor
Show me how to do that
Connect the screen to the breadboard.
The headers on the side of the screen
with the small blue tab and arrow
should be the ones that attach to the
board. Pay attention to the orientation
of the screen, in these images, it is

upside down.
Show me how to do that
Connect the BL and +5V pins to power,
and GND to ground. Connect CS-LD to
pin 10, DC to pin 9, RESET to pin 8,
MOSI to pin 13, and SCK to pin 11. If
uyou're using a Leonardo, you'll be
using different pins. see the getting
started page for more details.
Show me how to do that
Code
To use the screen you must first
include the SPI and TFT libraries.
#include <SPI.h>
#include <TFT.h>
[Get Code]

Define the pins you're going to use for


controlling the screen, and create an
instance of the TFT library
namedTFTscreen. You'll reference that
object whenever you're working with
the screen.
#define cs 10
#define dc 9
#define rst 8
TFT TFTscreen = TFT(cs, dc, rst);
[Get Code]

Set up the cursor's x & y position. In


the example, it starts in the center of
the screen; determined by dividing the
height and width of the screen by 2.
Create a named pin for your erase
switch.
int xPos = LCDscreen.width()/2;
int yPos = LCDscreen.height()/2;
int erasePin = 2;
[Get Code]

In setup(), after declaring the erase pin


as an input, initialize the display and
clear the screen's background.
void setup() {
pinMode(erasePin, INPUT);
TFTscreen.begin();
TFTscreen.background(0,0,0);
}
[Get Code]

Read the values of the pots and map


them to smaller numbers.
void loop()
{
int xValue = analogRead(A0);
int yValue = analogRead(A1);

xPos = xPos + (map(xValue, 0, 1023, 2, -2));


yPos = yPos + (map(yValue, 0, 1023, -2, 2));
[Get Code]

You'll want to keep the cursor from


moving offscreen with a
few if() statements before you draw the
point.
if(xPos > 159){
(xPos = 159);
}

if(xPos < 0){


(xPos = 0);
}
if(yPos > 127){
(yPos = 127);
}
if(yPos < 0){
(yPos = 0);
}
TFTscreen.stroke(255,255,255);
TFTscreen.point(xPos,yPos);
[Get Code]

Finally, check the button. If it is being


pressed and is HIGH, clear the screen
with background().
if(digitalRead(erasePin) == HIGH){
TFTscreen.background(0,0,0);
}
delay(33);
}

TFT Color Picker

levels) for red and blue, 6-bits (64


levels) for green.
Hardware Required
Arduino Uno
Arduino TFT screen
breadboard
hookup wire
three 10-kilohm potentiometers
Circuit
Connect power and ground to the
breadboard.
Show me how to do that
Attach the three pots to the
breadboard, connecting their outside
legs to power and ground. the center
legs should connect to A0-A2.
Show me how to do that
Connect the LCD screen to the
breadboard. The headers on the side of
the screen with the small blue tab and
arrow should be the ones that attach to
the board. Pay attention to the
orientation of the screen, in these
images, it is upside down.
Show me how to do that
Connect the BL and +5V pins to power,
and GND to ground. Connect CS-LD to
pin 10, DC to pin 9, RESET to pin 8,
MOSI to pin 13, and SCK to pin 11. If
you're using a Leonardo, you'll be using
different pins. see the getting started
page for more details.
Show me how to do that
Code
To use the screen you must first
include the SPI and TFT libraries.
#include <SPI.h>
#include <TFT.h>
[Get Code]

This example for the Arduino TFT


screen reads the input of three analog
sensors, using the values to change
the screen's color.
Color on the TFT screen is handled as
8-bit numbers (0-255). However, the
library scales these values to 5-bits (32

Define the pins you're going to use for


controlling the screen, and create an
instance of the TFT library
namedTFTscreen. You'll reference that
object whenever you're working with
the screen.
#define cs 10
#define dc 9
#define rst 8
TFT TFTscreen = TFT(cs, dc, rst);
[Get Code]

In setup(), initialize the screen and clear


the background. Start serial
communication as well.
void setup() {
Serial.begin(9600);
TFTscreen.begin();
TFTscreen.background(255, 255, 255);
}
[Get Code]

In loop(), read the values fron the pots,


mapping them to values between 0255. with background(), set the mapped
background colors and print the values
to the serial monitor.
void loop() {
int redVal = map(analogRead(A0), 0, 1023, 0,
255);
int greenVal = map(analogRead(A1), 0, 1023,
0, 255);
int blueVal = map(analogRead(A2), 0, 1023, 0,
255);
TFTscreen.background(redVal, greenVal, blue
Val);

#define dc 9
#define rst 8
// pin definition for the Leonardo
// #define cs 7
// #define dc 0
// #define rst 1
#include <TFT.h> // Arduino LCD library
#include <SPI.h>
TFT TFTscreen = TFT(cs, dc, rst);
void setup() {
// begin serial communication
Serial.begin(9600);
// initialize the display
TFTscreen.begin();
// set the background to white
TFTscreen.background(255, 255, 255);
}
void loop() {
// read the values from your sensors and scale
them to 0-255
int redVal = map(analogRead(A0), 0, 1023, 0,
255);
int greenVal = map(analogRead(A1), 0, 1023,
0, 255);
int blueVal = map(analogRead(A2), 0, 1023, 0,
255);

Serial.print("background(");
Serial.print(redVal);
Serial.print(" , ");
Serial.print(greenVal);
Serial.print(" , ");
Serial.print(blueVal);
Serial.println(")");
delay(33);
}
[Get Code]

The complete sketch is below :

// draw the background based on the mapped


values
TFTscreen.background(redVal, greenVal, blue
Val);
// send the values to the serial monitor
Serial.print("background(");
Serial.print(redVal);
Serial.print(" , ");
Serial.print(greenVal);
Serial.print(" , ");
Serial.print(blueVal);
Serial.println(")");

/*
TFT Color Picker
This example for the Arduino screen reads the
input of
potentiometers or analog sensors attached to
A0, A1,
and A2 and uses the values to change the
screen's color.
This example code is in the public domain.
Created 15 April 2013 by Scott Fitzgerald
http://arduino.cc/en/Tutorial/TFTColorPicker
*/
// pin definition for the Uno
#define cs 10

// wait for a moment


delay(33);
}

TFT Graph

To use the screen you must first


include the SPI and TFT libraries.
#include <SPI.h>
#include <TFT.h>
[Get Code]

Define the pins you're going to use for


controlling the screen, and create an
instance of the TFT library
namedTFTscreen. You'll reference that
object whenever you're working with
the screen.

This example for the Arduino TFT


screen reads the value of a
potentiometer, and graphs it on screen.
This is similar to the serial
communication Graph example.
Hardware Required
Arduino Uno
Arduino TFT screen
breadboard
hookup wire
one 10-kilohm potentiometer
Circuit
Connect power and ground to the
breadboard.
Show me how to do that
Place the potentiometer on the
breadboard. Connect one side to
ground, and the other to power.
Connect the middle pin to A0.
Show me how to do that
Connect the TFT screen to the
breadboard. The headers on the side of
the screen with the small blue tab and
arrow should be the ones that attach to
the board. Pay attention to the
orientation of the screen, in these
images, it is upside down.
Show me how to do that
Connect the BL and +5V pins to power,
and GND to ground. Connect CS-LD to
pin 10, DC to pin 9, RESET to pin 8,
MOSI to pin 13, and SCK to pin 11. If
you're using a Leonardo, you'll be using
different pins. see the getting started
page for more details.
Show me how to do that
Code

#define cs 10
#define dc 9
#define rst 8
TFT TFTscreen = TFT(cs, dc, rst);
[Get Code]

Create a variable for holding the


position of the x-axis of the graph.
You'll increment this each loop().
In setup(), initialize the screen and make
the background a nice color.
int xPos = 0;
void setup(){
TFTscreen.begin();
TFTscreen.background(250,16,200);
}
[Get Code]

In loop(), read the value from the


potentiometer, and map it to a value
that fits in the screen's height.
void loop(){
int sensor = analogRead(A0);
int graphHeight = map(sensor,0,1023,0,LCDscr
een.height());
[Get Code]

Set the stroke color to something that


will stand out against the nice color you
chose for the background, and draw a
line from the bottom of the screen
based on the value of the sensor
TFTscreen.stroke(250,180,10);
TFTscreen.line(xPos, TFTscreen.height() graphHeight, xPos, TFTscreen.height());
[Get Code]

Before closing up loop(), check to make


sure the graph hasn't gone past the
edge of the screen. If it has, erase
everything, and start back at 0 on the xaxis.
if (xPos >= 160) {
xPos = 0;
TFTscreen.background(250,16,200);
}
else {

xPos++;
}
delay(16);

// draw a line in a nice color


TFTscreen.stroke(250,180,10);
TFTscreen.line(xPos, TFTscreen.height()drawHeight, xPos, TFTscreen.height());

}
[Get Code]

// if the graph has reached the screen edge


// erase the screen and start again
if (xPos >= 160) {
xPos = 0;
TFTscreen.background(250,16,200);
}
else {
// increment the horizontal position:
xPos++;
}

The complete sketch is below :


/*
TFT Graph
This example for an Arduino screen reads
the value of an analog sensor on A0, and
graphs the values on the screen.
This example code is in the public domain.
Created 15 April 2013 by Scott Fitzgerald
http://arduino.cc/en/Tutorial/TFTGraph
*/
#include <TFT.h> // Arduino LCD library
#include <SPI.h>
// pin definition for the Uno
#define cs 10
#define dc 9
#define rst 8
// pin definition for the Leonardo
// #define cs 7
// #define dc 0
// #define rst 1
TFT TFTscreen = TFT(cs, dc, rst);
// position of the line on screen
int xPos = 0;
void setup(){
// initialize the serial port
Serial.begin(9600);
// initialize the display
TFTscreen.begin();
// clear the screen with a pretty color
TFTscreen.background(250,16,200);
}
void loop(){
// read the sensor and map it to the screen
height
int sensor = analogRead(A0);
int drawHeight = map(sensor,0,1023,0,TFTscre
en.height());
// print out the height to the serial monitor
Serial.println(drawHeight);

delay(16);
}

WiFi library
The firmware for the WiFi shield has
changed in Arduino IDE 1.0.5. You are
recommended to install this update
per these instructions
With the Arduino WiFi Shield, this
library allows an Arduino board to
connect to the internet. It can serve as
either a server accepting incoming
connections or a client making outgoing
ones. The library supports WEP
and WPA2 Personal encryption, but
not WPA2 Enterprise. Also note, if the
SSID is not broadcast, the shield
cannot connect.
Arduino communicates with
the WiFi shield using the SPI bus. This
is on digital pins 11, 12, and 13 on the
Uno and pins 50, 51, and 52 on the
Mega. On both boards, pin 10 is used
as SS. On the Mega, the hardware SS
pin, 53, is not used but it must be kept
as an output or the SPI interface won't
work. Digital pin 7 is used as a
handshake pin between the Wifi shield
and the Arduino, and should not be
used.
The WiFi library is very similar to
the Ethernet library, and many of the
function calls are the same.
For additional information on
the WiFi shield, see the Getting Started
page and the WiFi shield hardware
page.

WiFi class
The WiFi class initializes the ethernet
library and network settings.
begin()
disconnect()
config()
setDNS()
SSID()
BSSID()
RSSI()
encryptionType()
scanNetworks()
getSocket()
macAddress()
IPAddress class
The IPAddress class provides
information about the network
configuration.
localIP()
subnetMask()
gatewayIP()
Server class
The Server class creates servers which
can send data to and receive data from
connected clients (programs running on
other computers or devices).
Server
WiFiServer()
begin()
available()
write()
print()
println()
Client class
The client class creates clients that can
connect to servers and send and
receive data.
Client
WiFiClient()
connected()
connect()
write()
print()
println()
available()
read()
flush()
stop()

UDP class
The UDP class enables UDP message
to be sent and received.
WiFiUDP
begin()
available()
beginPacket()
endPacket()
write()
parsePacket()
peek()
read()
flush()
stop()
remoteIP()
remotePort()

WiFi.begin()

Description
Initializes the WiFi library's network
settings and provides the current
status.
Syntax
WiFi.begin();
WiFi.begin(ssid);
WiFi.begin(ssid, pass);
WiFi.begin(ssid, keyIndex, key);
Parameters
ssid: the SSID (Service Set Identifier) is
the name of the WiFi network you want
to connect to.
keyIndex: WEP encrypted networks
can hold up to 4 different keys. This
identifies which key you are going to
use.
key: a hexadecimal string used as a
security code for WEP encrypted
networks.
pass: WPA encrypted networks use a
password in the form of a string for
security.
Returns
WL_CONNECTED when connected to
a network
WL_IDLE_STATUS when not
connected to a network, but powered
on
Example
#include <WiFi.h>

//SSID of your network


char ssid[] = "yourNetwork";
//password of your WPA Network
char pass[] = "secretPassword";
void setup()
{
WiFi.begin(ssid, pass);
}
void loop () {}

WiFi.disconnect()
Description
Disconnects the WiFi shield from the
current network.
Syntax
WiFi.disconnect();
Parameters
none

WiFi.config()
Description
WiFi.config() allows you to configure a
static IP address as well as change the
DNS, gateway, and subnet addresses
on the WiFi shield.
Unlike WiFi.begin() which automatically
configures the WiFi shield to use
DHCP, WiFi.config() allows you to
manually set the network address of
the shield.
Calling WiFi.config() before WiFi.begin() force
s begin() to configure the WiFi shield with
the network addresses specified
in config().
You can call WiFi.config() after WiFi.begin(),
but the shield will initialize with begin() in
the default DHCP mode. Once
the config() method is called, it will
change the network address as
requested.
Syntax
WiFi.config(ip);
WiFi.config(ip, dns);
WiFi.config(ip, dns, gateway);
WiFi.config(ip, dns, gateway, subnet);
Parameters
ip: the IP address of the device (array
of 4 bytes)
dns: the address for a DNS server.

gateway: the IP address of the network


gateway (array of 4 bytes). optional:
defaults to the device IP address with
the last octet set to 1
subnet: the subnet mask of the network
(array of 4 bytes). optional: defaults to
255.255.255.0
Returns
Nothing
Example
This example shows how to set the
static IP address, 192.168.0.177, of the
LAN network to the WiFi shield:
#include <SPI.h>
#include <WiFi.h>
// the IP address for the shield:
IPAddress ip(192, 168, 0, 177);
char ssid[] = "yourNetwork"; // your network
SSID (name)
char pass[] = "secretPassword"; // your network
password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;
void setup()
{
// Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while(true); // don't continue
}
WiFi.config(ip);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// print your WiFi shield's IP address:
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}

void loop () {}

WiFi.config()
Description
WiFi.config() allows you to configure a
static IP address as well as change the
DNS, gateway, and subnet addresses
on the WiFi shield.
Unlike WiFi.begin() which automatically
configures the WiFi shield to use
DHCP, WiFi.config() allows you to
manually set the network address of
the shield.
Calling WiFi.config() before WiFi.begin() force
s begin() to configure the WiFi shield with
the network addresses specified
in config().
You can call WiFi.config() after WiFi.begin(),
but the shield will initialize with begin() in
the default DHCP mode. Once
the config() method is called, it will
change the network address as
requested.
Syntax
WiFi.config(ip);
WiFi.config(ip, dns);
WiFi.config(ip, dns, gateway);
WiFi.config(ip, dns, gateway, subnet);
Parameters
ip: the IP address of the device (array
of 4 bytes)
dns: the address for a DNS server.
gateway: the IP address of the network
gateway (array of 4 bytes). optional:
defaults to the device IP address with
the last octet set to 1
subnet: the subnet mask of the network
(array of 4 bytes). optional: defaults to
255.255.255.0
Returns
Nothing
Example
This example shows how to set the
static IP address, 192.168.0.177, of the
LAN network to the WiFi shield:
#include <SPI.h>
#include <WiFi.h>
// the IP address for the shield:
IPAddress ip(192, 168, 0, 177);

char ssid[] = "yourNetwork"; // your network


SSID (name)
char pass[] = "secretPassword"; // your network
password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;
void setup()
{
// Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while(true); // don't continue
}
WiFi.config(ip);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// print your WiFi shield's IP address:
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
void loop () {}

WiFi.setDNS()
Description
WiFi.setDNS() allows you to configure the
DNS (Domain Name System) server.
Syntax
WiFi.setDNS(dns_server1)
WiFi.setDNS(dns_server1,
dns_server2)
Parameters
dns_server1: the IP address of the
primary DNS server
dns_server2: the IP address of the
secondary DNS server

Returns
Nothing
Example
This example shows how to set the
Google DNS (8.8.8.8). You can set it as
an object IPAddress.
#include <SPI.h>
#include <WiFi.h>
// the IP address for the shield:
IPAddress dns(8, 8, 8, 8); //Google dns
char ssid[] = "yourNetwork"; // your network
SSID (name)
char pass[] = "secretPassword"; // your network
password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;
void setup()
{
// Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while(true); // don't continue
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// print your WiFi shield's IP address:
WiFi.setDNS(dns);
Serial.print("Dns configured.");
}
void loop () {
}

WiFi.SSID()
Description
Gets the SSID of the current network

Syntax
WiFi.SSID();
WiFi.SSID(wifiAccessPoint)
Parameters
wifiAccessPoint: specifies from which
network to get the information
Returns
A string containing the SSID
the WiFi shield is currently connected
to.
string containing name of network
requested.
Example
#include <SPI.h>
#include <WiFi.h>
//SSID of your network
char ssid[] = "yourNetwork";
int status = WL_IDLE_STATUS;
radio's status

// the Wifi

void setup()
{
// initialize serial:
Serial.begin(9600);
// scan for existing networks:
Serial.println("Scanning available networks...");
scanNetworks();
// attempt to connect using WEP encryption:
Serial.println("Attempting to connect to open
network...");
status = WiFi.begin(ssid);
Serial.print("SSID: ");
Serial.println(ssid);
}
void loop () {}
void scanNetworks() {
// scan for nearby networks:
Serial.println("** Scan Networks **");
byte numSsid = WiFi.scanNetworks();
// print the list of networks seen:
Serial.print("SSID List:");
Serial.println(numSsid);
// print the network number and name for each
network found:
for (int thisNet = 0; thisNet<numSsid; thisNet++
){
Serial.print(thisNet);
Serial.print(") Network: ");
Serial.println(WiFi.SSID(thisNet));
}

WiFi.RSSI()
Description
Gets the signal strength of the
connection to the router
Syntax
WiFi.RSSI();
WiFi.RSSI(wifiAccessPoint);
Parameters
wifiAccessPoint: specifies from which
network to get the information
Returns
long : the current RSSI /Received
Signal Strength in dBm
Example
#include <SPI.h>
#include <WiFi.h>
//SSID of your network
char ssid[] = "yourNetwork";
//password of your WPA Network
char pass[] = "secretPassword";
void setup()
{
WiFi.begin(ssid, pass);

Returns
long : the current RSSI /Received
Signal Strength in dBm
Example
#include <SPI.h>
#include <WiFi.h>
//SSID of your network
char ssid[] = "yourNetwork";
//password of your WPA Network
char pass[] = "secretPassword";
void setup()
{
WiFi.begin(ssid, pass);
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// if you are connected, print out info about the
connection:
else {
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("RSSI:");
Serial.println(rssi);
}
}
void loop () {}

if (WiFi.status() != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// if you are connected, print out info about the
connection:
else {
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("RSSI:");
Serial.println(rssi);
}
}

WiFi.scanNetworks()

void loop () {}

#include <SPI.h>
#include <WiFi.h>

WiFi.RSSI()
Description
Gets the signal strength of the
connection to the router
Syntax
WiFi.RSSI();
WiFi.RSSI(wifiAccessPoint);
Parameters
wifiAccessPoint: specifies from which
network to get the information

Description
Scans for available WiFi networks and
returns the discovered number
Syntax
WiFi.scanNetworks();
Parameters
none
Returns
byte : number of discovered networks
Example

char ssid[] = "yourNetwork"; // the name of


your network
int status = WL_IDLE_STATUS; // the Wifi
radio's status
byte mac[6];
your Wifi shield
void setup()
{
Serial.begin(9600);

// the MAC address of

status = WiFi.begin(ssid);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// if you are connected, print your MAC
address:
else {
Serial.println("** Scan Networks **");
byte numSsid = WiFi.scanNetworks();
Serial.print("SSID List:");
Serial.println(numSsid);
}
}
void loop () {}

WiFi.getSocket()
Description
gets the first socket available
Syntax
WiFi.getSocket();
Parameters
none
Returns
int : the first socket available

WiFi.macAddress()
Description
Gets the MAC Address of
your WiFi shield
Syntax
WiFi.macAddress(mac);
Parameters
mac: a 6 byte array to hold the MAC
address
Returns
byte array : 6 bytes representing the
MAC address of your shield
Example

void setup()
{
Serial.begin(9600);
status = WiFi.begin(ssid);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// if you are connected, print your MAC
address:
else {
WiFi.macAddress(mac);
Serial.print("MAC: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);
}
}
void loop () {}

WiFi.localIP()
Description
Gets the WiFi shield's IP address
Syntax
WiFi.localIP();
Parameters
none
Returns
the IP address of the shield
Example
#include <WiFi.h>
char ssid[] = "yourNetwork";
network

//SSID of your

#include <SPI.h>
#include <WiFi.h>

int status = WL_IDLE_STATUS;


radio's status

char ssid[] = "yourNetwork"; // the name of


your network
int status = WL_IDLE_STATUS; // the Wifi
radio's status

IPAddress ip;
your shield

byte mac[6];
your Wifi shield

// the MAC address of

void setup()
{
// initialize serial:
Serial.begin(9600);
WiFi.begin(ssid);

// the Wifi

// the IP address of

if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// if you are connected, print out info about the
connection:
else {
//print the local IP address
ip = WiFi.localIP();
Serial.println(ip);
}
}
void loop () {}

WiFi.subnetMask()
Description
Gets the WiFi shield's subnet mask
Syntax
WiFi.subnet();
Parameters
none
Returns
the subnet mask of the shield
Example
#include <WiFi.h>
int status = WL_IDLE_STATUS;
radio's status

// the Wifi

//SSID of your network


char ssid[] = "yourNetwork";
//password of your WPA Network
char pass[] = "secretPassword";
IPAddress ip;
IPAddress subnet;
IPAddress gateway;
void setup()
{
WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// if you are connected, print out info about the
connection:
else {
// print your subnet mask:
subnet = WiFi.subnetMask();
Serial.print("NETMASK: ");
Serial.println();
}
}

void loop () {
}

WiFi.gatewayIP()
Description
Gets the WiFi shield's gateway IP
address.
Syntax
WiFi.gatewayIP();
Parameters
none
Returns
An array containing the shield's
gateway IP address
Example
(:source lang=arduino tabwidth=4;)
1. include <SPI.h>
2. include <WiFi.h>
int status = WL_IDLE_STATUS; // the
Wifi radio's status
//SSID of your network char ssid[] =
"yourNetwork"; //password of your
WPA Network char pass[] =
"secretPassword";
IPAddress gateway;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// if you are connected, print out info about the
connection:
else {
// print your gateway address:
gateway = WiFi.gatewayIP();
Serial.print("GATEWAY: ");
Serial.println(gateway);
}

}
void loop () {} (:sourceend:)

Server
Description
Server is the base class for
all WiFi server based calls. It is not
called directly, but invoked whenever
you use a function that relies on it.

WiFiServer()

Description
Creates a server that listens for
incoming connections on the specified
port.
Syntax
Server(port);
Parameters
port: the port to listen on (int)
Returns
None
Example
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "myNetwork";
// your network
SSID (name)
char pass[] = "myPassword"; // your network
password
int status = WL_IDLE_STATUS;

Returns
None
Example
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "lamaison";
// your network
SSID (name)
char pass[] = "tenantaccess247"; // your
network password
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
// initialize serial:
Serial.begin(9600);
Serial.println("Attempting to connect to WPA
network...");
Serial.print("SSID: ");
Serial.println(ssid);

WiFiServer server(80);

status = WiFi.begin(ssid, pass);


if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
else {
server.begin();
Serial.print("Connected to wifi. My address:");
IPAddress myAddress = WiFi.localIP();
Serial.println(myAddress);

void setup() {
// initialize serial:
Serial.begin(9600);
Serial.println("Attempting to connect to WPA
network...");
Serial.print("SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
else {
server.begin();
Serial.print("Connected to wifi. My address:");
IPAddress myAddress = WiFi.localIP();
Serial.println(myAddress);
}
}
void loop() {
}

begin()
Description
Tells the server to begin listening for
incoming connections.
Syntax
server.begin()
Parameters
None

}
}
void loop() {
}

available()
Description
Gets a client that is connected to the
server and has data available for
reading. The connection persists when
the returned client object goes out of
scope; you can close it by
calling client.stop().
available() inherits from
the Stream utility class.
Syntax
server.available()
Parameters
None

Returns
a Client object; if no Client has data
available for reading, this object will
evaluate to false in an if-statement
Example
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "Network";
// your network
SSID (name)
char pass[] = "myPassword"; // your network
password
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
// initialize serial:
Serial.begin(9600);
Serial.println("Attempting to connect to WPA
network...");
Serial.print("SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
else {
server.begin();
Serial.print("Connected to wifi. My address:");
IPAddress myAddress = WiFi.localIP();
Serial.println(myAddress);
}
}
void loop() {
// listen for incoming clients
WiFiClient client = server.available();
if (client) {
if (client.connected()) {
Serial.println("Connected to client");
}
// close the connection:
client.stop();
}
}

write()
Description
Write data to all the clients connected
to a server.
Syntax
server.write(data)

Parameters
data: the value to write (byte or char)
Returns
byte : the number of bytes written. It is
not necessary to read this.
Example
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork";
char pass[] = "yourPassword";
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
// initialize serial:
Serial.begin(9600);
Serial.println("Attempting to connect to WPA
network...");
Serial.print("SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
else {
server.begin();
}
}
void loop() {
// listen for incoming clients
WiFiClient client = server.available();
if (client == true) {
// read bytes from the incoming client and
write them back
// to any clients connected to the server:
server.write(client.read());
}
}

print()
Description
Print data to all the clients connected to
a server. Prints numbers as a
sequence of digits, each an ASCII
character (e.g. the number 123 is sent
as the three characters '1', '2', '3').
Syntax
server.print(data)
server.print(data, BASE)
Parameters
data: the data to print (char, byte, int,
long, or string)

BASE (optional): the base in which to


print numbers: BIN for binary (base 2),
DEC for decimal (base 10), OCT for
octal (base 8), HEX for hexadecimal
(base 16).
Returns
byte print() will return the number of
bytes written, though reading that
number is optional

Parameters
none
Example

println()

int status = WL_IDLE_STATUS;


IPAddress server(74,125,115,105); // Google

Description
Prints data, followed by a newline, to all
the clients connected to a server. Prints
numbers as a sequence of digits, each
an ASCII character (e.g. the number
123 is sent as the three characters '1',
'2', '3').
Syntax
server.println()
server.println(data)
server.println(data, BASE)
Parameters
data (optional): the data to print (char,
byte, int, long, or string)
BASE (optional): the base in which to
print numbers: DEC for decimal (base
10), OCT for octal (base 8), HEX for
hexadecimal (base 16).
Returns
byte
println() will return the number of bytes
written, though reading that number is
optional

Client()
Description
Client is the base class for
all WiFi client based calls. It is not
called directly, but invoked whenever
you use a function that relies on it.

WiFiClient()
Description
Creates a client that can connect to to
a specified internet IP address and port
as defined in client.connect().
Syntax
WiFiClient()

#include <SPI.h>
#include <WiFi.h>
char ssid[] = "myNetwork";
// your network
SSID (name)
char pass[] = "myPassword"; // your network
password

// Initialize the client library


WiFiClient client;
void setup() {
Serial.begin(9600);
Serial.println("Attempting to connect to WPA
network...");
Serial.print("SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
// don't do anything else:
while(true);
}
else {
Serial.println("Connected to wifi");
Serial.println("\nStarting connection...");
// 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.0");
client.println();
}
}
}
void loop() {
}

connected()
Description
Whether or not the client is connected.
Note that a client is considered
connected if the connection has been
closed but there is still unread data.
Syntax
client.connected()
Parameters
none

Returns
Returns true if the client is connected,
false if not.
Example
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "myNetwork";
// your network
SSID (name)
char pass[] = "myPassword"; // your network
password
int status = WL_IDLE_STATUS;
IPAddress server(74,125,115,105); // Google
// Initialize the client library
WiFiClient client;
void setup() {
Serial.begin(9600);
Serial.println("Attempting to connect to WPA
network...");
Serial.print("SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
// don't do anything else:
while(true);
}
else {
Serial.println("Connected to wifi");
Serial.println("\nStarting connection...");
// 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.0");
client.println();
}
}
}
void loop() {
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}

connect()
Description
Connect to the IP address and port
specified in the constructor. The return
value indicates success or failure.
connect() also supports DNS lookups
when using a domain name
(ex:google.com).
Syntax
client.connect(ip, port)
client.connect(URL, port)
Parameters
ip: the IP address that the client will
connect to (array of 4 bytes)
URL: the domain name the client will
connect to (string, ex.:"arduino.cc")
port: the port that the client will connect
to (int)
Returns
Returns true if the connection
succeeds, false if not.
Example
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "myNetwork";
// your network
SSID (name)
char pass[] = "myPassword"; // your network
password
int status = WL_IDLE_STATUS;
char servername[]="google.com"; // remote
server we will connect to
WiFiClient client;
void setup() {
Serial.begin(9600);
Serial.println("Attempting to connect to WPA
network...");
Serial.print("SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
// don't do anything else:
while(true);
}
else {
Serial.println("Connected to wifi");
Serial.println("\nStarting connection...");
// if you get a connection, report back via
serial:
if (client.connect(servername, 80)) {
Serial.println("connected");

// Make a HTTP request:


client.println("GET /search?q=arduino
HTTP/1.0");
client.println();
}
}
}
void loop() {
}

write()
Description
Write data to the server the client is
connected to.
Syntax
client.write(data)
Parameters
data: the byte or char to write
Returns
byte: the number of characters written.
it is not necessary to read this value.

print()
Description
Print data to the server that a client is
connected to. Prints numbers as a
sequence of digits, each an ASCII
character (e.g. the number 123 is sent
as the three characters '1', '2', '3').
Syntax
client.print(data)
client.print(data, BASE)
Parameters
data: the data to print (char, byte, int,
long, or string)
BASE (optional): the base in which to
print numbers:, DEC for decimal (base
10), OCT for octal (base 8), HEX for
hexadecimal (base 16).
Returns
byte : returns the number of bytes
written, though reading that number
is optional

println()
Description
Print data, followed by a carriage return
and newline, to the server a client is
connected to. Prints numbers as a
sequence of digits, each an ASCII

character (e.g. the number 123 is sent


as the three characters '1', '2', '3').
Syntax
client.println()
client.println(data)
client.print(data, BASE)
Parameters
data (optional): the data to print (char,
byte, int, long, or string)
BASE (optional): the base in which to
print numbers: DEC for decimal (base
10), OCT for octal (base 8), HEX for
hexadecimal (base 16).
Returns
byte: return the number of bytes
written, though reading that number is
optional

available()
Description
Returns the number of bytes available
for reading (that is, the amount of data
that has been written to the client by
the server it is connected to).
available() inherits from
the Stream utility class.
Syntax
client.available()
Parameters
none
Returns
The number of bytes available.
Example
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "myNetwork";
// your network
SSID (name)
char pass[] = "myPassword"; // your network
password
int status = WL_IDLE_STATUS;
char servername[]="google.com"; // Google
WiFiClient client;
void setup() {
Serial.begin(9600);
Serial.println("Attempting to connect to WPA
network...");
Serial.print("SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);

if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
// don't do anything else:
while(true);
}
else {
Serial.println("Connected to wifi");
Serial.println("\nStarting connection...");
// if you get a connection, report back via
serial:
if (client.connect(servername, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /search?q=arduino
HTTP/1.0");
client.println();
}
}
}

flush() inherits from the Stream utility


class.
Syntax
client.flush()
Parameters
none
Returns
none

stop()
Disconnect from the server
Syntax
client.stop()
Parameters
none
Returns
none

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

WiFiUDP
Description
Creates a named instance of
the WiFi UDP class that can send and
receive UDP messages.
Syntax
WiFiUDP
Parameters
none

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


if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
for(;;)
;
}
}

read()
Read the next byte received from the
server the client is connected to (after
the last call to read()).
read() inherits from the Stream utility
class.
Syntax
client.read()
Parameters
none
Returns
The next byte (or character), or -1 if
none is available.

flush()
Discard any bytes that have been
written to the client but not yet read.

WiFi : WiFiUDP.begin()
Description
Initializes the WiFi UDP library and
network settings.
Starts WiFiUDP socket, listening at
local port PORT */
Syntax
WiFiUDP.begin(port);
Parameters
port: the local port to listen on (int)
Returns
1: if successful
0: if there are no sockets available to
use
WiFi : WiFiUDP.available()

available()
Description
Get the number of bytes (characters)
available for reading from the buffer.
This is data that's already arrived.

This function can only be successfully


called after WiFiUDP.parsePacket().
available() inherits from
the Stream utility class.
Syntax
WiFiUDP.available()
Parameters
None
Returns
the number of bytes available in the
current packet
0: if parsePacket hasn't been called yet
WiFi : WiFiUDP.beginPacket()
Description
Starts a connection to write UDP data
to the remote connection
Syntax
WiFiUDP.beginPacket(hostName,
port);
WiFiUDP.beginPacket(hostIp, port);
Parameters
hostName: the address of the remote
host. It accepts a character string or
an IPAddress
hostIp: the IP address of the remote
connection (4 bytes)
port: the port of the remote connection
(int)
Returns
1: if successful
0: if there was a problem with the
supplied IP address or port

WiFi : WiFiUDP.parsePacket()
Description
It starts processing the next available
incoming packet, checks for the
presence of a UDP packet, and reports
the size. parsePacket() must be called
before reading the buffer
with UDP.read().
Syntax
UDP.parsePacket();
Parameters
None
Returns
the size of the packet in bytes
0: if no packets are available
WiFi : WiFiUDP.peek()

peek()

WiFi : WiFiUDP.endPacket()
Description
Called after writing UDP data to the
remote connection. It finishes off the
packet and send it.
Syntax
WiFiUDP.endPacket();
Parameters
None
Returns
1: if the packet was sent successfully
0: if there was an error
WiFi : WiFiUDP.write()
Description
Writes UDP data to the remote
connection. Must be wrapped

between beginPacket()
and endPacket(). beginPacket()
initializes the packet of data, it is not
sent until endPacket() is called.
Syntax
WiFiUDP.write(byte);
WiFiUDP.write(buffer, size);
Parameters
byte: the outgoing byte
buffer: the outgoing message
size: the size of the buffer
Returns
single byte into the packet
bytes size from buffer into the packet

Read a byte from the file without


advancing to the next one. That is,
successive calls to peek() will return
the same value, as will the next call to
read().
This function inherited from the Stream
class. See the Stream class main page
for more information.
Syntax
WiFiUDP.peek()
Parameters
none
Returns
b: the next byte or character
-1: if none is available
WiFi : WiFiUDP.read()

Description
Reads UDP data from the specified
buffer. If no arguments are given, it will
return the next character in the buffer.
This function can only be successfully
called after WiFiUDP.parsePacket().
Syntax
WiFiUDP.read();
WiFiUDP.read(buffer, len);
Parameters
buffer: buffer to hold incoming packets
(char*)
len: maximum size of the buffer (int)
Returns
b: the characters in the buffer (char)
size: the size of the buffer
-1: if no buffer is available

Parameters
None
Returns
4 bytes : the IP address of the host who
sent the current incoming packet
WiFi : WiFIUDP.remotePort()
Description
Gets the port of the remote UDP
connection.
This function must be called
after UDP.parsePacket().
Syntax
UDP.remotePort();
Parameters
None
Returns
The port of the host who sent the
current incoming packet

flush()
Discard any bytes that have been
written to the client but not yet read.
flush() inherits from the Stream utility
class.
Syntax
WiFiUDP.flush()
Parameters
none
Returns
none

stop()
Description
Disconnect from the server. Release
any resource being used during the
UDP session.
Syntax
WiFiUDP.stop()
Parameters
none
Returns
none
WiFi : WiFiUDP.remoteIP()
Description
Gets the IP address of the remote
connection.
This function must be called
after WiFiUDP.parsePacket().
Syntax
WiFiUDP.remoteIP();

Connect No Encryption
This example shows you how to
connect to an open (not encrypted)
802.11b/g network with the
Arduino WiFi shield. Your Arduino's
serial monitor will provide information
about the connection once it has
connected.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.

// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to open
SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the data:
Serial.print("You're connected to the network");
printCurrentNet();
printWifiData();
}

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
This example connects to an unencrypted Wifi
network.
Then it prints the MAC address of the Wifi
shield,
the IP address obtained, and other network
details.

void loop() {
// check the network connection once every 10
seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);

Circuit:
* WiFi shield attached
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <WiFi.h>
char ssid[] = "yourNetwork"; // the name of
your network
int status = WL_IDLE_STATUS; // the Wifi
radio's status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");

// print your subnet mask:


IPAddress subnet = WiFi.subnetMask();
Serial.print("NetMask: ");
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print("Gateway: ");
Serial.println(gateway);
}

void printCurrentNet() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're
attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
Serial.print(bssid[5],HEX);
Serial.print(":");
Serial.print(bssid[4],HEX);
Serial.print(":");
Serial.print(bssid[3],HEX);
Serial.print(":");
Serial.print(bssid[2],HEX);
Serial.print(":");
Serial.print(bssid[1],HEX);
Serial.print(":");
Serial.println(bssid[0],HEX);

WEP network passwords are


hexadecimal strings known as keys. A
WEP network can have 4 different
keys; each key is assigned a "Key
Index" value. For WEP encrypted
networks, you need the SSID, the key,
and key number.

// print the received signal strength:


long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption,HEX);
}

Connect With WEP


This example shows you how to
connect to a WEP encrypted 802.11b/g
network with the Arduino WiFi shield.
Your Arduino's serial monitor will
provide information about the
connection once it has connected.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
This example connects to a WEP-encrypted
Wifi network.
Then it prints the MAC address of the Wifi
shield,
the IP address obtained, and other network
details.
If you use 40-bit WEP, you need a key that is
10 characters long,
and the characters must be hexadecimal (0-9 or
A-F).
e.g. for 40-bit, ABBADEAF01 will work, but
ABBADEAF won't work
(too short) and ABBAISDEAF won't work (I and
S are not
hexadecimal characters).
For 128-bit, you need a string that is 26
characters long.
D0D0DEADF00DABBADEAFBEADED will work
because it's 26 characters,
all in the 0-9, A-F range.
Circuit:
* WiFi shield attached

created 13 July 2010


by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <WiFi.h>

// print your MAC address:


byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);

char ssid[] = "yourNetwork";


// your
network SSID (name)
char key[] = "D0D0DEADF00DABBADEAFBEA
DED";
// your network key
int keyIndex = 0;
// your
network key Index number
int status = WL_IDLE_STATUS;
//
the Wifi radio's status
}
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WEP
network, SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, keyIndex, key);
// wait 10 seconds for connection:
delay(10000);

void printCurrentNet() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're
attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
Serial.print(bssid[5],HEX);
Serial.print(":");
Serial.print(bssid[4],HEX);
Serial.print(":");
Serial.print(bssid[3],HEX);
Serial.print(":");
Serial.print(bssid[2],HEX);
Serial.print(":");
Serial.print(bssid[1],HEX);
Serial.print(":");
Serial.println(bssid[0],HEX);

// print the received signal strength:


long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);

// once you are connected :


Serial.print("You're connected to the network");
printCurrentNet();
printWifiData();

// print the encryption type:


byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption,HEX);
Serial.println();

}
void loop() {
// check the network connection once every 10
seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);

Connect With WPA


This example shows you how to
connect to a WPA2 Personal encrypted
802.11b/g network with the
Arduino WiFi shield. Your Arduino's
serial monitor will provide information

about the connection once it has


connected.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.
For networks
using WPA/WPA2 Personal encryption,
you need the SSID and password. The
shield will not connect to networks
using WPA2 Enterprise encryption.

Circuit:
* WiFi shield attached
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network
SSID (name)
char pass[] = "secretPassword"; // your network
password
int status = WL_IDLE_STATUS; // the Wifi
radio's status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA
SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the data:
Serial.print("You're connected to the network");
printCurrentNet();
printWifiData();

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
This example connects to an unencrypted Wifi
network.
Then it prints the MAC address of the Wifi
shield,
the IP address obtained, and other network
details.

}
void loop() {
// check the network connection once every 10
seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();

Serial.print("IP Address: ");


Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);

out information about the board and the


networks it can see. It will not connect
to a network.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
Open your serial monitor to view the
networks the WiFi shield can see. The
Arduino may not see as many networks
as your computer.

}
void printCurrentNet() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're
attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
Serial.print(bssid[5],HEX);
Serial.print(":");
Serial.print(bssid[4],HEX);
Serial.print(":");
Serial.print(bssid[3],HEX);
Serial.print(":");
Serial.print(bssid[2],HEX);
Serial.print(":");
Serial.print(bssid[1],HEX);
Serial.print(":");
Serial.println(bssid[0],HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption,HEX);
Serial.println();
}

Connect With WPA


This example scans for 802.11b/g
networks with the Arduino WiFi shield.
Your Arduino's serial monitor will print

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
This example prints the Wifi shield's MAC
address, and
scans for available Wifi networks using the Wifi
shield.
Every ten seconds, it scans again. It doesn't
actually
connect to any network, so no encryption
scheme is specified.
Circuit:
* WiFi shield attached
created 13 July 2010

by dlf (Metodo2 srl)


modified 21 Junn 2012
by Tom Igoe and Jaymes Dec
*/
#include <SPI.h>
#include <WiFi.h>
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// Print WiFi MAC address:
printMacAddress();
// scan for existing networks:
Serial.println("Scanning available networks...");
listNetworks();
}
void loop() {
delay(10000);
// scan for existing networks:
Serial.println("Scanning available networks...");
listNetworks();
}
void printMacAddress() {
// the MAC address of your Wifi shield
byte mac[6];
// print your MAC address:
WiFi.macAddress(mac);
Serial.print("MAC: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);
}
void listNetworks() {
// scan for nearby networks:
Serial.println("** Scan Networks **");

int numSsid = WiFi.scanNetworks();


if (numSsid == -1)
{
Serial.println("Couldn't get a wifi connection");
while(true);
}
// print the list of networks seen:
Serial.print("number of available networks:");
Serial.println(numSsid);
// print the network number and name for each
network found:
for (int thisNet = 0; thisNet<numSsid; thisNet++
){
Serial.print(thisNet);
Serial.print(") ");
Serial.print(WiFi.SSID(thisNet));
Serial.print("\tSignal: ");
Serial.print(WiFi.RSSI(thisNet));
Serial.print(" dBm");
Serial.print("\tEncryption: ");
printEncryptionType(WiFi.encryptionType(this
Net));
}
}
void printEncryptionType(int thisType) {
// read the encryption type and print out the
name:
switch (thisType) {
case ENC_TYPE_WEP:
Serial.println("WEP");
break;
case ENC_TYPE_TKIP:
Serial.println("WPA");
break;
case ENC_TYPE_CCMP:
Serial.println("WPA2");
break;
case ENC_TYPE_NONE:
Serial.println("None");
break;
case ENC_TYPE_AUTO:
Serial.println("Auto");
break;
}
}

WiFi Chat Server


A simple server that distributes any
incoming messages to all connected
clients. To use, open a terminal
window, telnet to your WiFi shield's IP
address, and type away. Any incoming
text will be sent to all connected clients
(including the one typing). Additionally,
you will be able to see the client's input
in your serial monitor as well.
Hardware Required

Arduino WiFi Shield


Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.
For networks
using WPA/WPA2 Personal encryption,
you need the SSID and password. The
shield will not connect to networks
using WPA2 Enterprise encryption.
WEP network passwords are
hexadecimal strings known as keys. A
WEP network can have 4 different
keys; each key is assigned a "Key
Index" value. For WEP encrypted
networks, you need the SSID, the key,
and key number.

A simple server that distributes any incoming


messages to all
connected clients. To use telnet to your
device's IP address and type.
You can see the client's input in the serial
monitor as well.
This example is written for a network using
WPA encryption. For
WEP or WPA, change the Wifi.begin() call
accordingly.
Circuit:
* WiFi shield attached
created 18 Dec 2009
by David A. Mellis
modified 31 May 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network
SSID (name)
char pass[] = "secretPassword"; // your
network password (use for WPA, or use as key
for WEP)
int keyIndex = 0;
// your network key
Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(23);
boolean alreadyConnected = false; // whether or
not the client was connected previously
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
Chat Server

// check for the presence of the shield:


if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change

this line if using open or WEP network:


status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// start the server:
server.begin();
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() {
// wait for a new client:
WiFiClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clead out the input buffer:
client.flush();
Serial.println("We have a new client");
client.println("Hello, client!");
alreadyConnected = true;
}
if (client.available() > 0) {
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
}
void printWifiStatus() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

WiFi Xively Client


This example shows you how to
answer a HTTP request using

a WiFi shield. Specifically, it connects


to xively.com, a free datalogging site.
The example requires that you set up a
xively.com account, as well as a xively
feed (for more information on setting up
an input feed, please click here).
Your WiFi shield will then connect to
that feed and upload sensor data every
10 seconds.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
One analog sensor to attached
to AnalogIn pin 0
Software Required

xively.com account
xively.com feed that accepts two data
items
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.
For networks
using WPA/WPA2 Personal encryption,
you need the SSID and password. The
shield will not connect to networks
using WPA2 Enterprise encryption.
WEP network passwords are
hexadecimal strings known as keys. A
WEP network can have 4 different
keys; each key is assigned a "Key
Index" value. For WEP encrypted
networks, you need the SSID, the key,
and key number.

Circuit:
* Analog sensor attached to analog in 0
* Wifi shield attached to pins 10, 11, 12, 13
created 13 Mar 2012
modified 31 May 2012
by Tom Igoe
modified 8 Nov 2013
by Scott Fitzgerald
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>
#define APIKEY
"YOUR API KEY GOES
HERE" // replace your xively api key here
#define FEEDID
00000
//
replace your feed ID
#define USERAGENT
"My Arduino
Project" // user agent is the project name
char ssid[] = "yourNetwork";
// your network
SSID (name)
char pass[] = "secretPassword"; // your network
password
int status = WL_IDLE_STATUS;

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
Wifi Xively sensor client
This sketch connects an analog sensor to
Xively (http://www.xively.com)
using an Arduino Wifi shield.
This example is written for a network using
WPA encryption. For
WEP or WPA, change the Wifi.begin() call
accordingly.
This example has been updated to use version
2.0 of the Xively API.
To make it work, create a feed with a
datastream, and give it the ID
sensor1. Or change the code below to match
your feed.

// initialize the library instance:


WiFiClient client;
// 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(216,52,233,121);
//
numeric IP for api.xively.com
//char server[] = "api.xively.com"; // name
address for xively API
unsigned long lastConnectionTime = 0;
//
last time you connected to the server, in
milliseconds
boolean lastConnected = false;
// state
of the connection last time through the main loop
const unsigned long postingInterval = 10*1000; /
/delay between updates to xively.com
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);

}
String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// if there's incoming data from the net
connection.
// send it out the serial port. This is for
debugging
// purposes only:
while (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was
one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds
have passed since
// your last connection, then connect again and
send data:
if (!client.connected() && (millis() lastConnectionTime > postingInterval)) {
sendData(sensorReading);
}
// store the state of the connection for next time
through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the
server:
void sendData(int thisData) {

// if there's a successful connection:


if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in
bytes:
// 8 bytes for "sensor1," + number of digits of
the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT
request:
client.print("sensor1,");
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made
or attempted:
lastConnectionTime = millis();
}
// This method calculates the number of digits in
the
// sensor reading. Since each digit of the ASCII
decimal
// representation is a byte, the number of digits
equals
// the number of bytes:
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue / 10;
while (dividend > 0) {
dividend = dividend / 10;

digits++;
}
// return the number of digits:
return digits;
}
void printWifiStatus() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");

internet for this example. You will need


to change the network settings in the
sketch to correspond to your particular
networks SSID.
For networks
using WPA/WPA2 Personal encryption,
you need the SSID and password. The
shield will not connect to networks
using WPA2 Enterprise encryption.
WEP network passwords are
hexadecimal strings known as keys. A
WEP network can have 4 different
keys; each key is assigned a "Key
Index" value. For WEP encrypted
networks, you need the SSID, the key,
and key number.

WiFi Xively Client String


This example shows you how to
answer a HTTP request using
a WiFi shield. Specifically, it connects
to xively.com, a free datalogging site.
The example requires that you set up a
xively.com account, as well as a xively
feed (for more information on setting up
an input feed, please click here).
Your WiFi shield will then connect to
that feed and upload sensor data every
10 seconds.
Additionally, this example shows how
to send sensor data as a string.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
One analog sensor to attached
to AnalogIn pin 0
Software Required

xively.com account
xively.com feed that accepts two data
items
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.

Code:
/*
Wifi Xively sensor client with Strings
This sketch connects an analog sensor to
Xively (http://www.xively.com)
using a Arduino Wifi shield.
This example is written for a network using
WPA encryption. For
WEP or WPA, change the Wifi.begin() call
accordingly.
This example has been updated to use version
2.0 of the xively.com API.
To make it work, create a feed with a
datastream, and give it the ID
sensor1. Or change the code below to match
your feed.
This example uses the String library, which is
part of the Arduino core from
version 0019.

server:
//IPAddress server(216,52,233,121);
//
numeric IP for api.xively.com
char server[] = "api.xively.com"; // name
address for xively API
unsigned long lastConnectionTime = 0;
//
last time you connected to the server, in
milliseconds
boolean lastConnected = false;
// state
of the connection last time through the main loop
const unsigned long postingInterval = 10*1000;
//delay between updates to xively.com
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}

Circuit:
* Analog sensor attached to analog in 0
* Wifi shield attached to pins 10, 11, 12, 13
created 16 Mar 2012
modified 31 May 2012
by Tom Igoe
modified 8 Sept 2012
by Scott Fitzgerald
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>

String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);

#define APIKEY
"YOUR API KEY GOES
HERE" // replace your xively api key here
#define FEEDID
00000
//
replace your feed ID
#define USERAGENT
"My Arduino
Project" // user agent is the project name

char ssid[] = "yourNetwork";


// your network
SSID (name)
char pass[] = "secretPassword"; // your network
password

void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// convert the data to a String to send it:

int status = WL_IDLE_STATUS;


// initialize the library instance:
WiFiClient client;
// if you don't want to use DNS (and reduce your
sketch size)
// use the numeric IP instead of the name for the

}
// you're connected now, so print out the status:
printWifiStatus();

String dataString = "sensor1,";


dataString += sensorReading;
// you can append multiple readings to this
String if your
// xively feed is set up to handle multiple
values:
int otherSensorReading = analogRead(A1);
dataString += "\nsensor2,";

dataString += otherSensorReading;

else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made
or attempted:
lastConnectionTime = millis();
}

// if there's incoming data from the net


connection.
// send it out the serial port. This is for
debugging
// purposes only:
while (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was
one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}

void printWifiStatus() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);

// if you're not connected, and ten seconds


have passed since
// your last connection, then connect again and
send data:
if (!client.connected() && (millis() lastConnectionTime > postingInterval)) {
sendData(dataString);
}
// store the state of the connection for next time
through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the
server:
void sendData(String thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(thisData.length());
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT
request:
client.println(thisData);
}

// print the received signal strength:


long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

WiFi Web Client


This example shows you how to make
a HTTP request using a WiFi shield. It
returns a Google search for the term
"Arduino". The results of this search
are viewable as HTML through your
Arduino's serial window.
This example is written for a network
using WPA encryption. For WEP or
WPA, change the Wifi.begin() call
accordingly.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the

sketch to correspond to your particular


networks SSID.
For networks
using WPA/WPA2 Personal encryption,
you need the SSID and password. The
shield will not connect to networks
using WPA2 Enterprise encryption.
WEP network passwords are
hexadecimal strings known as keys. A
WEP network can have 4 different
keys; each key is assigned a "Key
Index" value. For WEP encrypted
networks, you need the SSID, the key,
and key number.

* WiFi shield attached


created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network
SSID (name)
char pass[] = "secretPassword"; // your
network password (use for WPA, or use as key
for WEP)
int keyIndex = 0;
// your network key
Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// 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)
// 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):
WiFiClient client;

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
Web client
This sketch connects to a website
(http://www.google.com)
using a WiFi shield.
This example is written for a network using
WPA encryption. For
WEP or WPA, change the Wifi.begin() call
accordingly.
This example is written for a network using
WPA encryption. For
WEP or WPA, change the Wifi.begin() call
accordingly.
Circuit:

void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}

Serial.println("Connected to wifi");
printWifiStatus();
Serial.println("\nStarting connection to
server...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected to server");
// 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();
}
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting from server.");
client.stop();
// do nothing forevermore:
while(true);
}
}
void printWifiStatus() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

WiFi Web Client Repeating


This example shows you how to make
repeated HTTP requests using
a WiFi shield. It connects
tohttp://www.arduino.cc/latest.txt. The

content of the page is viewable through


your Arduino's serial window.
This example is written for a network
using WPA encryption. For WEP or
WPA, change the Wifi.begin() call
accordingly.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.
For networks
using WPA/WPA2 Personal encryption,
you need the SSID and password. The
shield will not connect to networks
using WPA2 Enterprise encryption.
WEP network passwords are
hexadecimal strings known as keys. A
WEP network can have 4 different
keys; each key is assigned a "Key
Index" value. For WEP encrypted
networks, you need the SSID, the key,
and key number.

Serial.println("WiFi shield not present");


// don't continue:
while (true);

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:

}
String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");

/*
Repeating Wifi Web Client
This sketch connects to a a web server and
makes a request
using an Arduino Wifi shield.
Circuit:
* WiFi shield attached to pins SPI pins and pin 7
created 23 April 2012
modified 31 May 2012
by Tom Igoe
modified 13 Jan 2014
by Federico Vanzati
http://arduino.cc/en/Tutorial/WifiWebClientRepe
ating
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork";
// your network
SSID (name)
char pass[] = "secretPassword"; // your network
password
int keyIndex = 0;
// your network key
Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// Initialize the Wifi client library
WiFiClient client;
// server address:
char server[] = "www.arduino.cc";
//IPAddress server(64,131,82,241);
unsigned long lastConnectionTime = 0;
//
last time you connected to the server, in
milliseconds
const unsigned long postingInterval = 10L * 100
0L; // delay between updates, in milliseconds
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {

// attempt to connect to Wifi network:


while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() {
// if there's incoming data from the net
connection.
// send it out the serial port. This is for
debugging
// purposes only:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if ten seconds have passed since your last
connection,
// then connect again and send data:
if (millis() lastConnectionTime > postingInterval) {
httpRequest();
}
}
// this method makes a HTTP connection to the
server:
void httpRequest() {
// close any connection before send a new
request.
// This will free the socket on the WiFi shield
client.stop();
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.println("GET /latest.txt HTTP/1.1");
client.println("Host: www.arduino.cc");
client.println("User-Agent: ArduinoWiFi/1.1");
client.println("Connection: close");
client.println();

// note the time that the connection was made:


lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");

used to control the slave select pin on


the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.
For networks
using WPA/WPA2 Personal encryption,
you need the SSID and password. The
shield will not connect to networks
using WPA2 Enterprise encryption.
WEP network passwords are
hexadecimal strings known as keys. A
WEP network can have 4 different
keys; each key is assigned a "Key
Index" value. For WEP encrypted
networks, you need the SSID, the key,
and key number.

WiFi Web Server


In this example, you will use
your WiFi Shield and your Arduino to
create a simple Web server. Using
the WiFi library, your device will be able
to answer a HTTP request with
your WiFI shield. After opening a
browser and navigating to
your WiFishield's IP address, your
Arduino will respond with just enough
HTML for a browser to display the input
values from all six analog pins.
This example is written for a network
using WPA encryption. For WEP or
WPA, change the Wifi.begin() call
accordingly.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
(optional) Six analog sensors attached
to Analog in Pins 0-5
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
WiFi Web Server
A simple web server that shows the value of the
analog input pins.
using a WiFi shield.
This example is written for a network using
WPA encryption. For
WEP or WPA, change the Wifi.begin() call
accordingly.

Circuit:
* WiFi shield attached
* Analog inputs attached to pins A0 through A5
(optional)
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork";
// your network
SSID (name)
char pass[] = "secretPassword"; // your network
password
int keyIndex = 0;
// your network key
Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin();
// you're connected now, so print out the status:
printWifiStatus();

WiFiClient 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 closed after completion of the
response
client.println("Refresh: 5"); // refresh the
page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog input
pin
for (int analogChannel = 0; analogChanne
l < 6; analogChannel++) {
int sensorReading = analogRead(analog
Channel);
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 disonnected");

}
}
void loop() {
// listen for incoming clients

void printWifiStatus() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

Send and Receive UDP String


This sketch waits for a UDP packet on
a local port. When a valid packet is
received, an acknowledge packet is
sent back to the client on a specified
outgoing port.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
WiFi UDP Send and Receive String
This sketch wait an UDP packet on localPort
using a WiFi shield.
When a packet is received an Acknowledge
packet is sent to the client on port remotePort
Circuit:
* WiFi shield attached
created 30 December 2012
by dlf (Metodo2 srl)
*/
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
char ssid[] = "yourNetwork"; // your network
SSID (name)
char pass[] = "secretPassword"; // your
network password (use for WPA, or use as key
for WEP)
int keyIndex = 0;
// your network key
Index number (needed only for WEP)
unsigned int localPort = 2390;
listen on

// local port to

char packetBuffer[255]; //buffer to hold incoming


packet

char ReplyBuffer[] = "acknowledged";


string to send back

// a

Serial.println(packetBuffer);
// send a reply, to the IP address and port that
sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remot
ePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
}

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

void printWifiStatus() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());

// check for the presence of the shield:


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

// print your WiFi shield's IP address:


IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);

String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");

// print the received signal strength:


long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");

// attempt to connect to Wifi network:


while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid);

// wait 10 seconds for connection:


delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
Serial.println("\nStarting connection to
server...");
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) packetBuffer[len] = 0;
Serial.println("Contents:");

Network Time Protocol (NTP) Client


In this example, you will use
your WiFi Shield and your Arduino to
query a Network Time Protocol (NTP)
server. This way, your Arduino can get
the time from the Internet.
Hardware Required
Arduino WiFi Shield
Shield-compatible Arduino board
Circuit
The WiFi shield uses pins 10, 11, 12,
and 13 for the SPI connection to
the HDG104 module. Digital pin 4 is
used to control the slave select pin on
the SD card.
You should have access to a 802.11b/g
wireless network that connects to the
internet for this example. You will need
to change the network settings in the
sketch to correspond to your particular
networks SSID.

unsigned int localPort = 2390;


listen for UDP packets

// local port to

IPAddress timeServer(129, 6, 15, 28); //


time.nist.gov NTP server
const int NTP_PACKET_SIZE = 48; // NTP time
stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffe
r to hold incoming and outgoing packets
// A UDP instance to let us send and receive
packets over UDP
WiFiUDP Udp;

image developed using Fritzing. For more


circuit examples, see the Fritzing project page

In the above image, the Arduino would


be stacked below the WiFi shield.
Code:
/*
Udp NTP Client
Get the time from a Network Time Protocol
(NTP) time server
Demonstrates use of UDP sendPacket and
ReceivePacket
For more on NTP time servers and the
messages needed to communicate with them,
see
http://en.wikipedia.org/wiki/Network_Time_Proto
col
created 4 Sep 2010
by Michael Margolis
modified 9 Apr 2012
by Tom Igoe

void setup()
{
// Open serial communications and wait for port
to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for
Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change
this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);

This code is in the public domain.


*/
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
char ssid[] = "mynetwork"; // your network SSID
(name)
char pass[] = "mypassword";
// your network
password
int keyIndex = 0;
// your network key
Index number (needed only for WEP)

}
Serial.println("Connected to wifi");
printWifiStatus();
Serial.println("\nStarting connection to
server...");
Udp.begin(localPort);
}
void loop()
{
sendNTPpacket(timeServer); // send an NTP
packet to a time server
// wait to see if a reply is available

delay(1000);
Serial.println( Udp.parsePacket() );
if ( Udp.parsePacket() ) {
Serial.println("packet received");
// We've received a packet, read the data from
it
Udp.read(packetBuffer, NTP_PACKET_SIZE)
; // read the packet into the buffer
//the timestamp starts at byte 40 of the
received packet and is four bytes,
// or two words, long. First, esxtract the two
words:
unsigned long highWord = word(packetBuffer[
40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[
42], packetBuffer[43]);
// combine the four bytes (two words) into a
long integer
// this is NTP time (seconds since Jan 1
1900):
unsigned long secsSince1900 = highWord <<
16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);
// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds,
that's 2208988800:
const unsigned long seventyYears = 2208988
800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 seventyYears;
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print("The UTC time is ");
// UTC is
the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print
the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
// In the first 10 minutes of each hour, we'll
want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the
minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 ) {
// In the first 10 seconds of each minute,
we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch % 60); // print the second
}
// wait ten seconds before asking for the time

again
delay(10000);
}
// send an NTP request to the time server at the
given address
unsigned long sendNTPpacket(IPAddress& addr
ess)
{
//Serial.println("1");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE)
;
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
//Serial.println("2");
packetBuffer[0] = 0b11100011; // LI, Version,
Mode
packetBuffer[1] = 0; // Stratum, or type of
clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock
Precision
// 8 bytes of zero for Root Delay & Root
Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
//Serial.println("3");
// all NTP fields have been given values, now
// you can send a packet requesting a
timestamp:
Udp.beginPacket(address, 123); //NTP
requests are to port 123
//Serial.println("4");
Udp.write(packetBuffer, NTP_PACKET_SIZE);
//Serial.println("5");
Udp.endPacket();
//Serial.println("6");
}
void printWifiStatus() {
// print the SSID of the network you're attached
to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

Wire Library
This library allows you to communicate
with I2C / TWI devices. On the Arduino
boards with the R3 layout (1.0 pinout), the
SDA (data line) and SCL (clock line) are on
the pin headers close to the AREF pin. The
Arduino Due has two I2C / TWI
interfaces SDA1 andSCL1 are near to the
AREF pin and the additional one is on pins
20 and 21.
As a reference the table below shows where
TWI pins are located on various Arduino
boards.
Board
Uno,
Ethernet
Mega2560
Leonardo
Due

I2C / TWI pins


A4 (SDA), A5 (SCL)
20 (SDA), 21 (SCL)
2 (SDA), 3 (SCL)
20 (SDA), 21
(SCL), SDA1, SCL1

As of Arduino 1.0, the library inherits from


the Stream functions, making it consistent
with other read/write libraries. Because of
this, send() and receive() have been
replaced with read() and write().
Note

There are both 7- and 8-bit versions


of I2C addresses. 7 bits identify the device,
and the eighth bit determines if it's being
written to or read from. The Wire library
uses 7 bit addresses throughout. If you have
a datasheet or sample code that uses 8 bit
address, you'll want to drop the low bit (i.e.
shift the value one bit to the right), yielding
an address between 0 and 127.

Functions
begin()
requestFrom()
beginTransmission()
endTransmission()
write()
available()
read()
onReceive()
onRequest()

Wire.begin()
Wire.begin(address)
Description
Initiate the Wire library and join
the I2C bus as a master or slave. This
should normally be called only once.

Parameters
address: the 7-bit slave address
(optional); if not specified, join the bus
as a master.
Returns
None

Wire.requestFrom()
Description
Used by the master to request bytes
from a slave device. The bytes may
then be retrieved with
the available() andread() functions.
As of Arduino 1.0.1, requestFrom()
accepts a boolean argument changing
its behavior for compatibility with
certain I2Cdevices.
If true, requestFrom() sends a stop
message after the request, releasing
the I2C bus.
If false, requestFrom() sends a restart
message after the request. The bus will
not be released, which prevents
another master device from requesting
between messages. This allows one
master device to send multiple
requests while in control.
The default value is true.
Syntax
Wire.requestFrom(address, quantity)
Wire.requestFrom(address, quantity,
stop)
Parameters
address: the 7-bit address of the device
to request bytes from
quantity: the number of bytes to
request
stop : boolean. true will send a stop
message after the request, releasing
the bus. false will continually send a
restart after the request, keeping the
connection active.
Returns
byte : the number of bytes returned
from the slave device

Wire.beginTransmission(addr
ess)

Description
Begin a transmission to the I2C slave
device with the given address.
Subsequently, queue bytes for
transmission with the write() function
and transmit them by
calling endTransmission().
Parameters
address: the 7-bit address of the device
to transmit to
Returns
None

Wire.endTransmission()

Description
Ends a transmission to a slave device
that was begun
by beginTransmission() and transmits
the bytes that were queued by write().
As of Arduino 1.0.1, endTransmission()
accepts a boolean argument changing
its behavior for compatibility with
certainI2C devices.
If true, endTransmission() sends a stop
message after transmission, releasing
the I2C bus.
If false, endTransmission() sends a
restart message after transmission.
The bus will not be released, which
prevents another master device from
transmitting between messages. This
allows one master device to send
multiple transmissions while in control.
The default value is true.
Syntax
Wire.endTransmission()
Wire.endTransmission(stop)
Parameters
stop : boolean. true will send a stop
message, releasing the bus after
transmission. false will send a restart,
keeping the connection active.
Returns
byte, which indicates the status of the
transmission:
0:success
1:data too long to fit in transmit buffer
2:received NACK on transmit of
address
3:received NACK on transmit of data

4:other error

write()
Description
Writes data from a slave device in
response to a request from a master, or
queues bytes for transmission from a
master to slave device (in-between
calls to beginTransmission() and
endTransmission()).
Syntax
Wire.write(value)
Wire.write(string)
Wire.write(data, length)
Parameters
value: a value to send as a single byte
string: a string to send as a series of
bytes
data: an array of data to send as bytes
length: the number of bytes to transmit
Returns
byte: write() will return the number of
bytes written, though reading that
number is optional
Example
#include <Wire.h>
byte val = 0;
void setup()
{
Wire.begin(); // join i2c bus
}
void loop()
{
Wire.beginTransmission(44); // transmit to
device #44 (0x2c)
// device address is specified
in datasheet
Wire.write(val);
// sends value byte
Wire.endTransmission(); // stop transmitting
val++;
// increment value
if(val == 64) // if reached 64th position (max)
{
val = 0; // start over from lowest value
}
delay(500);
}

Wire.available()

Description
Returns the number of bytes available
for retrieval with read(). This should be
called on a master device after a call
torequestFrom() or on a slave inside
the onReceive() handler.
available() inherits from
the Stream utility class.
Parameters
None
Returns
The number of bytes available for
reading.

Description
Registers a function to be called when
a slave device receives a transmission
from a master.
Parameters
handler: the function to be called when
the slave receives data; this should
take a single int parameter (the number
of bytes read from the master) and
return nothing, e.g.: void myHandler(int

read()

Wire.onRequest(handler)
Description
Register a function to be called when a
master requests data from this slave
device.
Parameters
handler: the function to be called, takes
no parameters and returns nothing,
e.g.: void myHandler()
Returns
None

Description
Reads a byte that was transmitted from
a slave device to a master after a call
to requestFrom() or was transmitted
from a master to a slave. read() inherits
from the Stream utility class.
Syntax
Wire.read()
Parameters
none
Returns
The next byte received
Example
#include <Wire.h>
void setup()
{
Wire.begin();
// join i2c bus (address
optional for master)
Serial.begin(9600); // start serial for output
}
void loop()
{
Wire.requestFrom(2, 6);
from slave device #2

// request 6 bytes

while(Wire.available()) // slave may send less


than requested
{
char c = Wire.read(); // receive a byte as
character
Serial.print(c);
// print the character
}
delay(500);
}

Wire.onReceive(handler)

numBytes)

Returns
None