Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
EEPROM Library
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;
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
begin()
localIP()
maintain()
IPAddress class
Server class
Server
EthernetServer()
begin()
available()
write()
print()
println()
Client class
Client
EthernetClient()
if (EthernetClient)
connected()
connect()
write()
print()
println()
available()
read()
flush()
stop()
EthernetUDP class
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
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
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 };
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();
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:
available()
Description
server.available()
Parameters
None
Returns
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)
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
read()
#include <Ethernet.h>
#include <EthernetUdp.h>
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
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
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
{
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++)
Returns
None
Example
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// local port
EthernetUDP Udp;
void setup() {
// 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[] = {
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
// local port to
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
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
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
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
Ethernet : UDP.remotePort()
Description
Gets the port of the remote UDP
connection.
// local port to
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.
Code:
/*
Chat Server
A simple server that distributes any
incoming messages to all
connected clients. To use telnet to your
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)
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.
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:
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.
Code:
/*
Repeating Web client
This sketch connects to a a web server and
makes a request
using a Wiznet Ethernet shield. You can
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.
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
}
}
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.
/*
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.
*/
#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;
Code
image developed using Fritzing. For more
circuit examples, see the Fritzing project page
/*
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();
#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;
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");
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);
// local port
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
}
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.*;
Code
/*
Udp NTP Client
Get the time from a Network Time Protocol
(NTP) time server
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.
*/
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
// local port
Serial.println(secsSince1900);
char c = client.read();
Serial.print(c);
}
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();
}
}
void loop() {
*/
#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
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)
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()
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
DIGITAL_MESSAGE
C-style strings,
uses stringCallbackFunction for the function
type
SYSEX_START
Library structure
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();
}
GSMClient class
GSMVoiceCall class
GSMVoiceCall
getVoiceCallStatus()
ready()
voiceCall()
answerCall()
hangCall()
retrieveCallingNumber()
GSM_SMS class
GSM_SMS
beginSMS()
ready()
endSMS()
available()
remoteNumber()
read()
write()
print()
peek()
flush()
GPRS class
GSMClient
ready()
connect()
beginWrite()
write()
endWrite()
connected()
read()
available()
peek()
flush()
stop()
GSMServer class
GSMServer
ready()
beginWrite()
write()
endWrite()
read()
available()
stop()
GSMModem class
GSMScanner class
GSMScanner
begin()
getCurrentCarrier()
getSignalStrength()
readNetworks()
GSMPIN class
GSMPIN
begin()
isPIN()
checkPIN()
checkPUK()
changePIN()
switchPIN()
checkReg()
getPINUsed()
setPINUsed()
GSMBand class
// 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
getVoiceCallStatus()
Description
Returns status of the voice call.
Syntax
voice.getVoiceCallStatus()
Parameters
none
Returns
char : IDLE_CALL, CALLING,
RECEIVINGCALL, TALKING
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
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;
voiceCall()
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()
{
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
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;
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
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;
}
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
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()
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);
Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");
}
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);
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 ""
Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");
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 ""
Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");
delay(1000);
}
GPRS constructor
// connection state
boolean notConnected = true;
Description
GPRS is the base class for all GPRS
functions, such as internet client and
server behaviors.
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();
}
}
}
}
}
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
{
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();
// 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();
// 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();
// 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.
Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan
}
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
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
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
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]
{
char inChar = Serial.read();
[Get Code]
// libraries
#include <GSM.h>
else
{
// PIN Number
;
// 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)
{
SIM card
Circuit
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_R
EADY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]
[Get Code]
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]
// 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");
}
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
[Get Code]
// 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
}
/*
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
void setup(){
Serial.begin(9600);
Serial.println("SMS Messages Receiver");
[Get Code]
char c;
if (sms.available())
{
[Get Code]
void loop()
{
char c;
Circuit:
* GSM shield
created 25 Feb 2012
by Javier Zorzano / TD
Serial.println("\nEND OF MESSAGE");
// delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");
void setup()
{
// initialize serial communications
Serial.begin(9600);
delay(1000);
}
#define GPRS_APN
"GPRS_APN"
#define GPRS_LOGIN "login"
#define GPRS_PASSWORD "password"
[Get Code]
(gprs.attachGPRS(GPRS_APN, GPRS_LO
GIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]
}
}
[Get Code]
[Get Code]
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(;;)
;
}
}
#define GPRS_APN
"GPRS_APN"
#define GPRS_LOGIN "login"
#define GPRS_PASSWORD "password"
[Get Code]
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
[Get Code]
if (client)
{
[Get Code]
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
{
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();
}
}
}
}
}
if (client)
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]
lastConnected = client.connected();
}
[Get Code]
[Get Code]
[Get Code]
// 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();
client.println(thisData);
}
[Get Code]
[Get Code]
// 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...");
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;
if(modem.begin())
Serial.println("modem.begin() succeeded");
else
Serial.println("ERROR, no modem answer.");
}
[Get Code]
Create an instance of
the GSMModem class:
GSMModem modem;
if(modem.getIMEI() != NULL)
{
Serial.println("Modem is functoning
properly");
}
[Get Code]
[Get Code]
void loop()
{
use_proxy = false;
Serial.println(oktext);
[Get Code]
[Get Code]
[Get Code]
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";
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]
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++;
}
}
}
}
);
void setup()
{
// initialize serial communications
Serial.begin(9600);
Serial.println("GSM networks scanner");
scannerNetworks.begin();
// 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()
Initialize an instance of
the GSMPin class.
GSMPIN PINManager;
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]
Serial.println(oktext);
}
else
{
Serial.println("Incorrect PUK or invalid new
PIN. Try again!.");
}
}
[Get Code]
void loop()
{
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();
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)
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");
}
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;
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
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
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
#include <LiquidCrystal.h>
void setup()
{
lcd.print("hello, world!");
}
void loop() {}
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
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
noBlink()
Description
Turns off the blinking LCD cursor.
Syntax
lcd.noBlink()
Parameters
lcd: a variable of type LiquidCrystal
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
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
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++) {
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
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).
Code
/*
LiquidCrystal Library - 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);
}
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.
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
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.
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.
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
http://arduino.cc/en/Tutorial/LiquidCrystalSerial
*/
// include the library code:
#include <LiquidCrystal.h>
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
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.
Code
/*
LiquidCrystal Library - scrollDisplayLeft() and
scrollDisplayRight()
SD Library
** 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;
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");
}
}
Serial.println("Removing example.txt...");
SD.remove("example.txt");
if (SD.exists("example.txt")){
Serial.println("example.txt exists.");
}
else {
Serial.println("example.txt doesn't exist.");
}
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);
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:
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
}
void loop()
{
// nothing happens after setup
}
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
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
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.
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
Schematic
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
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.
Code
// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.
#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
void setup()
{
myservo.attach(9); // attaches the servo on pin
9 to the servo object
}
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
Ardu
ino
Boar
d
a128
0 or
Meg
a256
0
SS
(m
ast
er)
10
53
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
(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:
slaveSelect
Pin:
slave device SS
pin
transferMo
de:
SPI_CONTINUE:
(Arduin
o Due
only)
(Optio
nal,
Arduin
o Due
only)
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]
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
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
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
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
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: 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);
}
void loop()
{
Stepper Library
Two Pins
Four Pins
Four Pins
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
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>
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
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
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
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>
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>
#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);
#define cs 10
#define dc 9
#define rst 8
void loop() {
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
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>
void setup() {
// initialize the screen
screen.begin();
#define cs 10
#define dc 9
#define rst 8
TFT screen = TFT(cs, dc, rst);
void setup() {
// initialize the screen
screen.begin();
stroke
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>
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>
#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);
void setup() {
// initialize the screen
screen.begin();
#define cs 10
#define dc 9
#define rst 8
void setup() {
// initialize the screen
screen.begin();
}
void loop() {
setTextSize
text
Description
Write text to the screen at the given
coordinates.
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
Example
#include <SPI.h>
#include <TFT.h>
#define cs 10
#define dc 9
#define rst 8
void loop() {
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>
#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
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>
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>
#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
void setup() {
// initialize the screen
screen.begin();
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);
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
#define dc 9
#define rst 8
void loop() {
}
circle
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>
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>
#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
void setup() {
// initialize the screen
screen.begin();
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
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
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
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
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
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
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() {
}
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);
}
#define cs 10
#define dc 9
#define rst 8
TFT TFTscreen = TFT(cs, dc, rst);
[Get Code]
TFTscreen.background(0, 0, 0);
TFTscreen.stroke(255,255,255);
TFTscreen.setTextSize(2);
TFTscreen.text("Sensor Value : ",0,0);
TFTscreen.setTextSize(5);
}
[Get Code]
void loop() {
String sensorVal = String(analogRead(A0));
sensorVal.toCharArray(sensorPrintout, 4);
[Get Code]
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
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]
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);
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;
}
[Get Code]
TFT EtchASketch
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 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]
/*
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
TFT Graph
#define cs 10
#define dc 9
#define rst 8
TFT TFTscreen = TFT(cs, dc, rst);
[Get Code]
xPos++;
}
delay(16);
}
[Get Code]
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>
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.
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);
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
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>
IPAddress ip;
your shield
byte mac[6];
your Wifi shield
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
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);
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)
Parameters
none
Example
println()
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
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");
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
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();
}
}
}
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
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.
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
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();
}
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");
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);
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);
}
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);
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();
}
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();
}
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();
}
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;
}
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) {
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");
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
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
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// convert the data to a String to send it:
}
// you're connected now, so print out the status:
printWifiStatus();
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();
}
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);
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");
}
}
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) {
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();
}
}
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");
}
// local port to
// 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());
String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");
// local port to
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);
}
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
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
Wire.onReceive(handler)
numBytes)
Returns
None