304
Libraries The Arduino environment can be extended through the use of libraries, just like most programming platforms. Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data. A number of libraries come installed with the IDE, but you can also download or create your own. See these instructions for details on installing libraries. There's also a tutorial on writing your own libraries . See the API Style Guide for information on making a good Arduino-style API for your library. To use a library in a sketch, select it from Sketch > Import Library. Standard Libraries EEPROM - reading and writing to "permanent" storage Ethernet - for connecting to the internet using the Arduino Ethernet Shield Firmata - for communicating with applications on the computer using a standard serial protocol. GSM - for connecting to a GSM/GRPS network with the GSM shield. LiquidCrystal - for controlling liquid crystal displays (LCDs) SD - for reading and writing SD cards Servo - for controlling servo motors SPI - for communicating with devices using the Serial Peripheral Interface (SPI) Bus SoftwareSerial - for serial communication on any digital pins. Version 1.0 and later of Arduino incorporate Mikal Hart 'sNewSoftSerial library as SoftwareSerial. Stepper - for controlling stepper motors TFT - for drawing text , images, and shapes on the Arduino TFT screen WiFi - for connecting to the internet using the Arduino WiFi shield Wire - Two Wire Interface (TWI/I2C) for sending and receiving data over a net of devices or sensors. The Matrix and Sprite libraries are no longer part of the core distribution. Due Only Libraries Audio - Play audio files from a SD card. Scheduler - Manage multiple non-blocking tasks. USBHost - Communicate with USB peripherals like mice and keyboards. Esplora Only Library Esplora - this library enable you to easily access to various sensors and actuators mounted on the Esplora board. Arduino Robot Library

api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  • Upload
    tranthu

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

Page 1: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

LibrariesThe Arduino environment can be extended through the use of libraries, just like most programming platforms. Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data. A number of libraries come installed with the IDE, but you can also download or create your own. See these instructions for details on installing libraries. There's also a tutorial on writing your own libraries.See the API Style Guide for information on making a good Arduino-style API for your library.To use a library in a sketch, select it from Sketch > Import Library.Standard Libraries

EEPROM  - reading and writing to "permanent" storage

Ethernet  - for connecting to the internet using the Arduino Ethernet Shield

Firmata  - for communicating with applications on the computer using a standard serial protocol.

GSM  - for connecting to a GSM/GRPS network with the GSM shield.

LiquidCrystal  - for controlling liquid crystal displays (LCDs)

SD  - for reading and writing SD cards Servo  - for controlling servo motors SPI  - for communicating with devices

using the Serial Peripheral Interface (SPI) Bus

SoftwareSerial  - for serial communication on any digital pins. Version 1.0 and later of Arduino incorporate Mikal Hart'sNewSoftSerial library as SoftwareSerial.

Stepper  - for controlling stepper motors TFT  - for drawing text , images, and

shapes on the Arduino TFT screen WiFi  - for connecting to the internet

using the Arduino WiFi shield Wire  - Two Wire Interface (TWI/I2C) for

sending and receiving data over a net of devices or sensors.

The Matrix and Sprite libraries are no longer part of the core distribution.Due Only Libraries

Audio  - Play audio files from a SD card. Scheduler  - Manage multiple non-

blocking tasks. USBHost  - Communicate with USB

peripherals like mice and keyboards.Esplora Only Library

Esplora  - this library enable you to easily access to various sensors and actuators mounted on the Esplora board.Arduino Robot Library

Robot  - this library enables easy access to the functions of the Arduino RobotArduino Yún Bridge Library

Bridge Library  - Enables communication between the Linux processor and the Arduino on the Yún.USB Libraries (Leonardo, Micro, Due, and Esplora)

Keyboard  - Send keystrokes to an attached computer.

Mouse  - Control cursor movement on a connected computer.Contributed LibrariesIf you're using one of these libraries, you need to install it first. See these instructions for details on installation. There's also a tutorial on writing your own libraries.Communication (networking and protocols):

Messenger  - for processing text-based messages from the computer

NewSoftSerial  - an improved version of the SoftwareSerial library

OneWire  - control devices (from Dallas Semiconductor) that use the One Wire protocol.

PS2Keyboard  - read characters from a PS2 keyboard.

Simple Message System  - send messages between Arduino and the computer

SSerial2Mobile  - send text messages or emails using a cell phone (via AT commands over software serial)

Page 2: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Webduino  - extensible web server library (for use with the Arduino Ethernet Shield)

X10  - Sending X10 signals over AC power lines

XBee  - for communicating with XBees in API mode

SerialControl  - Remote control other Arduinos over a serial connectionSensing:

Capacitive Sensing  - turn two or more pins into capacitive sensors

Debounce  - for reading noisy digital inputs (e.g. from buttons)Displays and LEDs:

GFX  - base class with standard graphics routines (by Adafruit Industries)

GLCD  - graphics routines for LCD based on the KS0108 or equivalent chipset.

Improved LCD library  fixes LCD initialization bugs in official Arduino LCD library

LedControl  - for controlling LED matrices or seven-segment displays with a MAX7221 or MAX7219.

LedControl  - an alternative to the Matrix library for driving multiple LEDs with Maxim chips.

LedDisplay  - control of a HCMS-29xx scrolling LED display.

Matrix  - Basic LED Matrix display manipulation library

PCD8544  - for the LCD controller on Nokia 55100-like displays (by Adafruit Industries)

Sprite  - Basic image sprite manipulation library for use in animations with an LED matrix

ST7735  - for the LCD controller on a 1.8", 128x160 TFT screen (by Adafruit Industries)Audio and Waveforms:

FFT  - frequency analysis of audio or other analog signals

Tone  - generate audio frequency square waves in the background on any microcontroller pinMotors and PWM:

TLC5940  - 16 channel 12 bit PWM controller.Timing:

DateTime  - a library for keeping track of the current date and time in software.

Metro  - help you time actions at regular intervals

MsTimer2  - uses the timer 2 interrupt to trigger an action every N milliseconds.Utilities:

PString  - a lightweight class for printing to buffers

Streaming  - a method to simplify print statements

EEPROM LibraryThe microcontroller on the Arduino board has EEPROM: memory whose values are kept when the board is turned off (like a tiny hard drive). This library enables you to read and write those bytes.The microcontrollers on the various Arduino boards have different amounts of EEPROM: 1024 bytes on the ATmega328, 512 bytes on the ATmega168 and ATmega8, 4 KB (4096 bytes) on the ATmega1280 and ATmega2560.Functions

read() write()

read()DescriptionReads a byte from the EEPROM. Locations that have never been written to have the value of 255.SyntaxEEPROM.read(address)Parametersaddress: the location to read from, starting from 0 (int)Returnsthe value stored in that location (byte)Example#include <EEPROM.h>

int a = 0;int value;

void setup()

Page 3: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

{ 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()DescriptionWrite a byte to the EEPROM.SyntaxEEPROM.write(address, value)Parametersaddress: the location to write to, starting from 0 (int)value: the value to write, from 0 to 255 (byte)ReturnsnoneNoteAn 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 libraryWith 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 making outgoing ones. The library supports up to four concurrent connection (incoming or outgoing or a combination).Arduino communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the W5100, but it must be kept as an output or the SPI interface won't work.

Page 4: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Ethernet classThe Ethernet class initializes the ethernet library and network settings.

begin() localIP() maintain()

IPAddress classThe IPAddress class works with local and remote IP addressing.

IPAddress() Server classThe Server class creates servers which can send data to and receive data from connected clients (programs running on other computers or devices).

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

Client classThe client class creates clients that can connect to servers and send and receive data.

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

EthernetUDP classThe EthernetUDP class enables UDP message to be sent and received.

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

Ethernet.begin()DescriptionInitializes the ethernet library and network settings.With version 1.0, the library supports DHCP. Using Ethernet.begin(mac) with

the proper network setup, the Ethernet shield will automatically obtain an IP address. This increases the sketch size significantly.SyntaxEthernet.begin(mac); Ethernet.begin(mac, ip); Ethernet.begin(mac, ip, dns); Ethernet.begin(mac, ip, dns, gateway); Ethernet.begin(mac, ip, dns, gateway, subnet); Parametersmac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.ip: the IP address of the device (array of 4 bytes)dns: the IP address of the DNS server (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1gateway: the IP address of the network gateway (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0ReturnsThe DHCP version of this function, Ethernet.begin(mac), returns an int: 1 on a successful DHCP connection, 0 on failure. The other versions don't return anything.Example#include <SPI.h>#include <Ethernet.h>

// the media access control (ethernet hardware) address for the shield:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  //the IP address for the shield:byte ip[] = { 10, 0, 0, 177 };    

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

Page 5: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

void loop () {}

Ethernet.localIP()DescriptionObtains the IP address of the Ethernet shield. Useful when the address is auto assigned through DHCP.SyntaxEthernet.localIP();ParametersnoneReturnsthe IP addressExample#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 shieldbyte 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()DescriptionAllows for the renewal of DHCP leases. When assigned an IP address via DHCP, ethernet devices are given a lease on the address for an amount of

time. With Ethernet.maintain(), it is possible to request a renewal from the DHCP server. Depending on the server's configuration, you may receive the same address, a new one, or none at all.Ethernet.maintain() was added to Arduino 1.0.1.SyntaxEthernet.maintain();ParametersnoneReturnsbyte:0: nothing happened1: renew failed2: renew success3: rebind fail4: rebind success

IPAddress()DescriptionDefines an IP address. It can be used to declare both local and remote addresses.SyntaxIPAddress(address);Parametersaddress: a comma delimited list representing the address (4 bytes, ex. 192, 168, 1, 1)ReturnsNoneExample#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 ipIPAddress 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 networkIPAddress ip(192, 168, 0, 2);

Page 6: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

  // initialize the ethernet device  Ethernet.begin(mac, ip, dnServer, gateway, subnet);  //print out the IP address  Serial.print("IP = ");  Serial.println(Ethernet.localIP());}

void loop() {}

ServerDescriptionServer 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()DescriptionCreate a server that listens for incoming connections on the specified port.SyntaxServer(port);Parametersport: the port to listen on (int)ReturnsNoneExample#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 23EthernetServer 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());  }}

begin()DescriptionTells the server to begin listening for incoming connections.Syntaxserver.begin()ParametersNoneReturnsNoneExample#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 23EthernetServer server = EthernetServer(23);

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

  // start listening for clients  server.begin();}

void loop(){

Page 7: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

available()DescriptionGets 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.Syntaxserver.available()ParametersNoneReturnsa Client object; if no Client has data available for reading, this object will evaluate to false in an if-statement (see the example below)Example#include <Ethernet.h>#include <SPI.h>

// the media access control (ethernet hardware) address for the shield:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  //the IP address for the shield:byte ip[] = { 10, 0, 0, 177 };    // the router's gateway address:byte gateway[] = { 10, 0, 0, 1 };// the subnet:byte subnet[] = { 255, 255, 0, 0 };

// telnet defaults to port 23EthernetServer server = EthernetServer(23);

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

  // start listening for clients  server.begin();}

void loop(){  // if an incoming client connects, there will be

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

write()DescriptionWrite data to all the clients connected to a server. This data is sent as a byte or series of bytes.Syntaxserver.write(val) server.write(buf, len)Parametersval: 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 bufferReturnsbytewrite() 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 23EthernetServer server = EthernetServer(23);

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

  // start listening for clients  server.begin();}

Page 8: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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()DescriptionPrint 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').Syntaxserver.print(data) server.print(data, BASE)Parametersdata: 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).Returnsbyteprint() will return the number of bytes written, though reading that number is optional

println()DescriptionPrint 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').Syntaxserver.println() server.println(data) server.println(data, BASE)

Parametersdata (optional): the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).Returnsbyteprintln() will return the number of bytes written, though reading that number is optional

ClientDescriptionClient 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()DescriptionCreates a client which can connect to a specified internet IP address and port (defined in the client.connect() function).SyntaxEthernetClient()ParametersNoneExample#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");

Page 9: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

Ethernet : if (EthernetClient)DescriptionIndicates if the specified Ethernet client is ready.Syntaxif (client)ParametersnoneReturnsboolean : 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 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(;;)      ;  }} 

connected()DescriptionWhether 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.Syntaxclient.connected()ParametersnoneReturnsReturns 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);

Page 10: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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 loop(){  if (client.available()) {    char c = client.read();    Serial.print(c);  }

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

connect()DescriptionConnects to a specified IP address and port. The return value indicates success or failure. Also supports DNS lookups when using a domain name.Syntaxclient.connect()client.connect(ip, port)client.connect(URL, port)Parametersip: 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)ReturnsReturns 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;

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

write()DescriptionWrite data to the server the client is connected to. This data is sent as a byte or series of bytes.Syntaxclient.write(val) client.write(buf, len)Parametersval: 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 bufferReturnsbytewrite() returns the number of bytes

Page 11: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

written. It is not necessary to read this value.

print()DescriptionPrint 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').Syntaxclient.print(data) client.print(data, BASE)Parametersdata: 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).Returnsbyte: returns the number of bytes written, though reading that number is optional

println()DescriptionPrint 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').Syntaxclient.println() client.println(data) client.print(data, BASE)Parametersdata (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).Returnsbyte: return the number of bytes written, though reading that number is optional

available()

DescriptionReturns 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.Syntaxclient.available()ParametersnoneReturnsThe number of bytes available.Example#include <Ethernet.h>#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 10, 0, 0, 177 };byte server[] = { 64, 233, 187, 99 }; // Google

EthernetClient client;

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

  delay(1000);

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

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

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

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

Page 12: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.Syntaxclient.read()ParametersnoneReturnsThe 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.flush() inherits from the Stream utility class.Syntaxclient.flush()ParametersnoneReturnsnone

stop()DescriptionDisconnect from the server.Syntaxclient.stop()ParametersnoneReturnsnoneEthernet : UDP.begin()DescriptionInitializes the ethernet UDP library and network settings.SyntaxEthernetUDP.begin(localPort); ParameterslocalPort: the local port to listen on (int)ReturnsNoneExample

#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;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;

void setup() {

  // start the Ethernet and UDP:

  Ethernet.begin(mac,ip);

  Udp.begin(localPort);

}

void loop() {

}

Ethernet : UDP.read()DescriptionReads UDP data from the specified buffer. If no arguments are given, it will return the next character in the buffer.

Page 13: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

This function can only be successfully called after UDP.parsePacket().SyntaxUDP.read();UDP.read(packetBuffer, MaxSize); ParameterspacketBuffer: buffer to hold incoming packets (char)MaxSize: maximum size of the buffer (int)Returnschar : returns the characters in the bufferExample#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;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

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

}

void loop() {

  int packetSize = Udp.parsePacket();  if(packetSize)  {    Serial.print("Received packet of size ");    Serial.println(packetSize);    Serial.print("From ");    IPAddress remote = Udp.remoteIP();    for (int i =0; i < 4; i++)    {      Serial.print(remote[i], DEC);      if (i < 3)      {

        Serial.print(".");      }    }    Serial.print(", port ");    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);    Serial.println("Contents:");    Serial.println(packetBuffer);}}Ethernet : UDP.write()DescriptionWrites 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.SyntaxUDP.write(message); UDP.write(buffer, size);Parametersmessage: the outgoing message (char)buffer: an array to send as a series of bytes (byte or char)size: the length of the bufferReturnsbyte : returns the number of characters sent. This does not have to be readExample

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

Page 14: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

unsigned int localPort = 8888;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;

void setup() {

  // start the Ethernet and UDP:

  Ethernet.begin(mac,ip);

  Udp.begin(localPort);

}

void loop() {

  Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());

    Udp.write("hello");

    Udp.endPacket();

}

Ethernet : UDP.beginPacket()DescriptionStarts a connection to write UDP data to the remote connectionSyntaxUDP.beginPacket(remoteIP, remotePort); ParametersremoteIP: the IP address of the remote connection (4 bytes)remotePort: the port of the remote connection (int)ReturnsNoneExample#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;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

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

}

void loop() {

  Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());    Udp.write("hello");    Udp.endPacket();

}

Ethernet : UDP.endPacket()DescriptionCalled after writing UDP data to the remote connection.SyntaxUDP.endPacket(); ParametersNoneReturnsNoneExample#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;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

Page 15: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

}

void loop() {

  Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());    Udp.write("hello");    Udp.endPacket();

}

Ethernet : UDP.parsePacket()DescriptionChecks for the presence of a UDP packet, and reports the size. parsePacket() must be called before reading the buffer with UDP.read().SyntaxUDP.parsePacket(); ParametersNoneReturnsint: the size of a received UDP packetExample

#include <SPI.h>         // needed for Arduino versions later than 0018#include <Ethernet.h>#include <EthernetUdp.h>         // UDP library from: [email protected] 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;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

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

  Serial.begin(9600);}

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

Ethernet : UDP.available()available()DescriptionGet 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.SyntaxUDP.available()ParametersNoneReturnsthe number of bytes available to readExample#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;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

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

Page 16: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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_MAX_SIZE);    Serial.println("Contents:");    Serial.println(packetBuffer); }}

stop()DescriptionDisconnect from the server. Release any resource being used during the UDP session.SyntaxEthernetUDP.stop()ParametersnoneReturnsnone

Ethernet : UDP.remoteIP()DescriptionGets the IP address of the remote connection.This function must be called after UDP.parsePacket().SyntaxUDP.remoteIP(); ParametersNone

Returns4 bytes : the IP address of the remote connectionExample

#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;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

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

void loop() {

  int packetSize = Udp.parsePacket();  if(packetSize)  {    Serial.print("Received packet of size ");    Serial.println(packetSize);    Serial.print("From IP : ");

    IPAddress remote = Udp.remoteIP();    //print out the remote connection's IP address    Serial.print(remote);

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

}

Ethernet : UDP.remotePort()DescriptionGets the port of the remote UDP connection.This function must be called after UDP.parsePacket().SyntaxUDP.remotePort(); 

Page 17: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

ParametersNoneReturnsint : the port of the UDP connection to a remote hostExample#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;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

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

}

void loop() {

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

    // read the packet into packetBufffer    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SI

ZE);    Serial.println("Contents:");    Serial.println(packetBuffer); }}Chat ServerA 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

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

Page 18: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the Ethernet shield.Schematic

Code:

/* Chat  Server  A simple server that distributes any incoming messages to all connected clients.  To use telnet to  your device's IP address and type. You can see the client's input in the serial monitor as well. Using an Arduino Wiznet Ethernet shield.   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.// 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 23EthernetServer 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

Page 19: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  }

  Serial.print("Chat server address:");  Serial.println(Ethernet.localIP());}

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

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

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

Web ClientThis 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

CircuitThe Ethernet shield allows you to connect a WizNet Ethernet controller to the Arduino via the SPI bus. It uses pins 10, 11, 12, and 13 for the SPI connection to the WizNet. Later models of the Ethernet shield also have an SD Card on board. Digital pin 4 is used to control the slave select pin on the SD card.

The shield should be connected to a network with an ethernet cable. You will need to change the network settings in the program to correspond to your network.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the Ethernet shield.Schematic

Page 20: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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 shieldbyte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server://IPAddress server(74,125,232,128);   // numeric IP for Google (no DNS)char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assignIPAddress 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:

Page 21: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    // try to congifure using IP address instead of DHCP:    Ethernet.begin(mac, ip);  }  // give the Ethernet shield a second to initialize:  delay(1000);  Serial.println("connecting...");

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

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

  // if the server's disconnected, stop the client:  if (!client.connected()) {    Serial.println();    Serial.println("disconnecting.");    client.stop();

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

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

tohttp://www.arduino.cc/latest.txt. The conent of the page is viewable through your Arduino's serial window.Hardware Required

Arduino Ethernet Shield Shield-compatible Arduino board

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the Ethernet shield.Schematic

Page 22: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

use the Arduino Ethernet shield, or  the Adafruit Ethernet shield, either one will work, as long as it's got a Wiznet Ethernet module on board.  This example uses DNS, by assigning the Ethernet client with a MAC address,  IP address, and DNS address.  Circuit: * Ethernet shield attached to pins 10, 11, 12, 13  created 19 Apr 2012 by Tom Igoe  http://arduino.cc/en/Tutorial/WebClientRepeating This code is in the public domain.  */

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

// assign a MAC address for the ethernet controller.// fill in your address here:byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};// fill in an available IP address on your network here,// for manual configuration:IPAddress ip(10,0,0,20);

// fill in your Domain Name Server address here:IPAddress myDns(1,1,1,1);

// initialize the library instance:EthernetClient client;

char server[] = "www.arduino.cc";

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in millisecondsboolean lastConnected = false;                 // state of the connection last time through the main loopconst unsigned long postingInterval = 60*1000;  // delay between updates, in milliseconds

void setup() {  // start serial port:

Page 23: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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 ServerIn 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

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

Page 24: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, your Arduino would be stacked below the Ethernet shield.Schematic

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

Page 25: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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

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

Page 26: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    client.stop();    Serial.println("client disconnected");  }}

Xively ClientThis 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 ShieldSoftware Required

xively.com account pachube.com feed that accepts two

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, your Arduino would be stacked below the Ethernet shield. You could also use an Arduino Ethernet board.Schematic

Page 27: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

 This example has been updated to use version 2.0 of the Xively.com API.  To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed.   Circuit: * Analog sensor attached to analog in 0 * Ethernet shield attached to pins 10, 11, 12, 13  created 15 March 2010 modified 9 Apr 2012 by Tom Igoe with input from Usman Haque and Joe Saavedra http://arduino.cc/en/Tutorial/XivelyClient This code is in the public domain.  */

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

#define APIKEY         "YOUR API KEY GOES HERE" // replace your xively api key here#define FEEDID         00000 // replace your feed ID#define USERAGENT      "My Project" // user agent is the project name

// assign a MAC address for the ethernet controller.// Newer Ethernet shields have a MAC address printed on a sticker on the shield// fill in your address here:byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

// fill in an available IP address on your network here,// for manual configuration:IPAddress ip(10,0,1,20);// initialize the library instance:EthernetClient client;

// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server:IPAddress server(216,52,233,122);      // numeric IP for api.xively.com//char server[] = "api.xively.com";   // name

Page 28: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

address for xively API

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in millisecondsboolean lastConnected = false;                 // state of the connection last time through the main loopconst unsigned long postingInterval = 10*1000; //delay between updates to Xively.com

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

 // start the Ethernet connection:  if (Ethernet.begin(mac) == 0) {    Serial.println("Failed to configure Ethernet using DHCP");    // DHCP failed, so use a fixed IP address:    Ethernet.begin(mac, ip);  }}

void loop() {  // read the analog sensor:  int sensorReading = analogRead(A0);   

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

  // if there's no net connection, but there was one last time  // through the loop, then stop the client:  if (!client.connected() && lastConnected) {    Serial.println();    Serial.println("disconnecting.");    client.stop();  }

  // if you're not connected, and ten seconds have passed since  // your last connection, then connect again

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

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

    // calculate the length of the sensor reading in bytes:    // 8 bytes for "sensor1," + number of digits of the data:    int thisLength = 8 + getLength(thisData);    client.println(thisLength);

    // last pieces of the HTTP PUT request:    client.println("Content-Type: text/csv");    client.println("Connection: close");    client.println();

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

Page 29: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

}

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

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

Xively Client using StringsThis example shows you how to answer a HTTP request using an Ethernet shield. Specifically, it connects to xively.com, a free datalogging site. The example requires that you set up a xively.com account, as well as a pachube feed (for more information on setting up an input feed, please click here). Your Ethernet shield will then connect to that feed and upload sensor data every 10 seconds.Additionally, this example shows how to send sensor data as a string.Hardware Required

Arduino Ethernet Shield or Arduino Ethernet board

Shield-compatible Arduino board Two analog sensors to attached to the

Ethernet ShieldSoftware Required

xively.com account xively.com feed that accepts one data

itemCircuitThe Ethernet shield allows you to connect a WizNet Ethernet controller to

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, your Arduino would be stacked below the Ethernet shield. Or you could use an Arduino Ethernet board.Schematic

Page 30: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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

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

#define APIKEY         "YOUR API KEY GOES HERE" // replace your Xively api key here#define FEEDID         00000 // replace your feed ID#define USERAGENT      "My Project" // user agent is the project name

// assign a MAC address for the ethernet controller.// 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;

Page 31: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

// 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 millisecondsboolean lastConnected = false;                 // state of the connection last time through the main loopconst unsigned long postingInterval = 10*1000;  //delay between updates to xively.com

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

  // give the ethernet module time to boot up:  delay(1000);  // start the Ethernet connection:  if (Ethernet.begin(mac) == 0) {    Serial.println("Failed to configure Ethernet using DHCP");    // DHCP failed, so use a fixed IP address:    Ethernet.begin(mac, ip);  }}

void loop() {  // read the analog sensor:  int sensorReading = analogRead(A0);     // convert the data to a String to send it:

  String dataString = "sensor1,";  dataString += sensorReading;

  // you can append multiple readings to this String if your  // xively feed is set up to handle multiple values:  int otherSensorReading = analogRead(A1);  dataString += "\nsensor2,";  dataString += otherSensorReading;

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

  // if there's no net connection, but there was one last time  // through the loop, then stop the client:  if (!client.connected() && lastConnected) {    Serial.println();    Serial.println("disconnecting.");    client.stop();  }

  // if you're not connected, and ten seconds have passed since  // your last connection, then connect again and send data:   if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {    sendData(dataString);  }  // store the state of the connection for next time through  // the loop:  lastConnected = client.connected();}

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

    // last pieces of the HTTP PUT request:    client.println("Content-Type: text/csv");    client.println("Connection: close");    client.println();

Page 32: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

Barometric Pressure Web ServerThis example shows how to use SPI communications to read data from a SCP1000 Barometric Pressure sensor, and how to then post that data to the web by using your Arduino/Ethernet Shield combo as a simple web server. Using the Ethernet library, your device will be able to answer HTTP requests by responding with just enough HTML for a browser to display the temperature and barometric pressure values outputted by your sensor. After completing your circuit and uploading the example code below, simply navigate to your Ethernet shield's IP address, in a browser, to see this information.See the Barometric Pressure Sensor example for more on how the sensor works.Hardware Required

SCP1000 Pressure Sensor Breakout Board

Arduino Ethernet ShieldCircuitYour Barometric Pressure sensor will be attached to pins 6,7, and 11 - 13 of your Arduino/Ethernet shield combo, and powered via your device's 3.3 volt output. Connect the DRDY (Data Ready) pin on your sensor to digital pin 6 on your combo, and the CSB pin (Chip Select) to digital pin 7. Your sensor's MOSI (Master Out Slave In) pin should then be connected to digital

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the Ethernet shield.Schematic

Page 33: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Code/*  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/product_info.php?products_id=8161 http://www.vti.fi/en/support/obsolete_products/pressure_sensors/  This sketch adapted from Nathan Seidle's SCP1000 example for PIC: http://www.sparkfun.com/datasheets/Senso

rs/SCP1000-Testing.zip  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  created 31 July 2010 by Tom Igoe */

#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 pressureconst int PRESSURE_LSB = 0x20;  //16 least significant bits of pressureconst 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;

Page 34: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

long lastReadingTime = 0;

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

  // start the Ethernet connection and the server:  Ethernet.begin(mac, ip);  server.begin();

  // initalize the  data ready and chip select pins:  pinMode(dataReadyPin, INPUT);  pinMode(chipSelectPin, OUTPUT);

  Serial.begin(9600);

  //Configure SCP1000 for low noise configuration:  writeRegister(0x02, 0x2D);  writeRegister(0x01, 0x03);  writeRegister(0x03, 0x02);

  // give the sensor and Ethernet shield time to set up:  delay(1000);

  //Set the sensor to high resolution mode tp start readings:  writeRegister(0x03, 0x0A);

}

void loop() {   // check for a reading no more than once a second.  if (millis() - lastReadingTime > 1000){    // if there's a reading ready, read it:    // don't do anything until the data ready pin is high:    if (digitalRead(dataReadyPin) == HIGH) {      getData();      // timestamp the last time you got a reading:      lastReadingTime = millis();    }  }

  // listen for incoming Ethernet connections:  listenForEthernetClients();}

void getData() {  Serial.println("Getting reading");

  //Read the temperature data  int tempData = readRegister(0x21, 2);

  // convert the temperature to celsius and display it:  temperature = (float)tempData / 20.0;

  //Read the pressure data highest 3 bits:  byte  pressureDataHigh = readRegister(0x1F, 1);     pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0

  //Read the pressure data lower 16 bits:  unsigned int pressureDataLow = readRegister(0x20, 2);      //combine the two parts into one 19-bit number:  pressure = ((pressureDataHigh << 16) | pressureDataLow)/4;

  Serial.print("Temperature: ");  Serial.print(temperature);  Serial.println(" degrees C");  Serial.print("Pressure: " + String(pressure));  Serial.println(" Pa");}

void listenForEthernetClients() {  // listen for incoming clients  EthernetClient client = server.available();  if (client) {    Serial.println("Got a client");    // an http request ends with a blank line    boolean currentLineIsBlank = true;    while (client.connected()) {      if (client.available()) {        char c = client.read();        // if you've gotten to the end of the line (received a newline        // character) and the line is blank, the http request has ended,        // so you can send a reply        if (c == '\n' && currentLineIsBlank) {          // send a standard http response header          client.println("HTTP/1.1 200 OK");          client.println("Content-Type: text/html");          client.println();          // print the current readings, in HTML format:          client.print("Temperature: ");          client.print(temperature);

Page 35: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

          client.print(" degrees C");          client.println("<br />");          client.print("Pressure: " + String(pressure));          client.print(" Pa");          client.println("<br />");            break;        }        if (c == '\n') {          // you're starting a new line          currentLineIsBlank = true;        }         else if (c != '\r') {          // you've gotten a character on the current line          currentLineIsBlank = false;        }      }    }    // give the web browser time to receive the data    delay(1);    // close the connection:    client.stop();  }} 

//Send a write command to SCP1000void writeRegister(byte registerName, byte registerValue) {  // 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); 

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

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

Arduino Ethernet Shield Shield-compatible Arduino board

Circuit

Page 36: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, your Arduino would be stacked below the Ethernet shield.Schematic

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

Page 37: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  A Processing sketch is included at the end of file that can be used to send  and received messages for testing with a computer.  created 21 Aug 2010 by Michael Margolis  This code is in the public domain. */

#include <SPI.h>         // needed for Arduino versions later than 0018#include <Ethernet.h>#include <EthernetUdp.h>         // UDP library from: [email protected] 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;      // local port to listen on

// buffers for receiving and sending datachar packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,char  ReplyBuffer[] = "acknowledged";       // a string to send back

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

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

  Serial.begin(9600);}

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

    // read the packet into packetBufffer    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);    Serial.println("Contents:");    Serial.println(packetBuffer);

    // send a reply, to the IP address and port that sent us the packet we received    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());    Udp.write(ReplyBuffer);    Udp.endPacket();  }  delay(10);}

/*  Processing sketch to run with this example =====================================================   // Processing UDP example to send and receive string data from Arduino   // press any key to send the "Hello Arduino" message    import hypermedia.net.*;  UDP udp;   // define the UDP object   void setup() { udp = new UDP( this, 6000 );   // create a new datagram connection on port 6000 //udp.log( true );         // <-- printout the connection activity udp.listen( true );           // and wait for

Page 38: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

incoming message    }  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  }  void receive( byte[] data ) {           // <-- default handler  //void receive( byte[] data, String ip, int port ) {   // <-- extended handler   for(int i=0; i < data.length; i++)  print(char(data[i]));   println();      } */

[Get Code]Processing CodeCopy 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.

Network Time Protocol (NTP) ClientIn this example, you will use your Ethernet Shield and your Arduino to query a Network Time Protocol (NTP) server. This way, your Arduino can get the time from the Internet.Hardware Required

Arduino Ethernet Shield Shield-compatible Arduino board

CircuitThe Ethernet shield allows you to connect a WizNet Ethernet controller to the Arduino via the SPI bus. It uses pins 10, 11, 12, and 13 for the SPI connection to the WizNet. Later models of the Ethernet shield also have an SD Card on board. Digital pin 4 is used to

control the slave select pin on the SD card.The shield should be connected to a network with an ethernet cable. You will need to change the network settings in the program to correspond to your network.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, your Arduino would be stacked below the Ethernet shield.Schematic

Page 39: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Code/*

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

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

    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.

 */

#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 shieldbyte mac[] = {    0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

unsigned int localPort = 8888;      // local port to listen for UDP packets

IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov NTP server// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov NTP server// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov NTP server

const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 

// A UDP instance to let us send and receive

Page 40: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

packets over UDPEthernetUDP Udp;

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

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

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

    // wait to see if a reply is available  delay(1000);    if ( Udp.parsePacket() ) {      // We've received a packet, read the data from it    Udp.read(packetBuffer,NTP_PACKET_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 = 2208988800UL;         // subtract seventy years:  unsigned long epoch = secsSince1900 - seventyYears;      // print Unix time:    Serial.println(epoch);                               

    // print the hour, minute and second:    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)    Serial.print(':');      if ( ((epoch % 3600) / 60) < 10 ) {      // In the first 10 minutes of each hour, we'll want a leading '0'      Serial.print('0');    }    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)    Serial.print(':');     if ( (epoch % 60) < 10 ) {      // In the first 10 seconds of each minute, we'll want a leading '0'      Serial.print('0');    }    Serial.println(epoch %60); // print the second  }  // wait ten seconds before asking for the time again  delay(10000); }

// send an NTP request to the time server at the given address unsigned long sendNTPpacket(IPAddress& address){

Page 41: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

  // all NTP fields have been given values, now  // you can send a packet requesting a timestamp:            Udp.beginPacket(address, 123); //NTP requests are to port 123  Udp.write(packetBuffer,NTP_PACKET_SIZE);  Udp.endPacket(); }

DNS Web ClientThis example connects to a named server using an Ethernet shield. The sketch illustrates how to connect using DHCP and DNS. When calling Ethernet.begin(mac), the Etehrnet library attempts to obtain an IP address using DHCP. Using DHCP significantly adds to the sketch size; be sure there is enough space to run the program.DNS lookup happens when client.connect(servername,port) is called. servername is a URL string, like "www.arduino.cc".Hardware Required

Arduino Ethernet Shield Shield-compatible Arduino board

CircuitThe Ethernet shield allows you to connect a WizNet Ethernet controller to

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, your Arduino would be stacked below the Ethernet shield.Code/*  DNS and DHCP-based Web client

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

 Circuit: * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009 by David A. Mellis modified 9 Apr 2012 by Tom Igoe, based on work by Adrian McEwen

 */

Page 42: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

#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 shieldbyte mac[] = {  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };char serverName[] = "www.google.com";

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

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

  // start the Ethernet connection:  if (Ethernet.begin(mac) == 0) {    Serial.println("Failed to configure Ethernet using DHCP");    // no point in carrying on, so do nothing forevermore:    while(true);  }  // give the Ethernet shield a second to initialize:  delay(1000);  Serial.println("connecting...");

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

  if (client.connect(serverName, 80)) {    Serial.println("connected");    // Make a HTTP request:    client.println("GET /search?q=arduino HTTP/1.0");    client.println();  }   else {    // kf you didn't get a connection to the server:    Serial.println("connection failed");  }}

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

  // if the server's disconnected, stop the client:  if (!client.connected()) {    Serial.println();    Serial.println("disconnecting.");    client.stop();

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

DHCP Chat ServerThis example connects to a Telnet server using an Ethernet shield. Messages from the server are printed out via the serial port. Messages can be sent to the remote server serially as well. The Serial monitor works well for this purpose.This version attempts to get an IP address using DHCP. An IP address can be assigned via DHCP when Ethernet.begin(mac) is called. Be careful, when using the DHCP extensions, sketch size increases significantly.Hardware Required

Arduino Ethernet Shield Shield-compatible Arduino board

Software Required A telnet server Alternatively, Processing has

a ChatServer example that works well for this purposeCircuitThe 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

Page 43: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Card on board. Digital pin 4 is used to control the slave select pin on the SD card.The shield should be connected to a network with an ethernet cable. You will need to change the network settings in the program to correspond to your network.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, your Arduino would be stacked below the Ethernet shield.Code/* DHCP Chat  Server  A simple server that distributes any incoming messages to all connected clients.  To use telnet to  your device's IP address and type. You can see the client's input in the serial monitor as well. Using an Arduino Wiznet Ethernet shield.   THis version attempts to get an IP address using DHCP  Circuit: * Ethernet shield attached to pins 10, 11, 12, 13  created 21 May 2011 modified 9 Apr 2012 by Tom Igoe Based on ChatServer example by David A. Mellis

  */

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

// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network.// gateway and subnet are optional:byte mac[] = {   0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };IPAddress ip(192,168,1, 177);IPAddress gateway(192,168,1, 1);IPAddress subnet(255, 255, 0, 0);

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

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

Page 44: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  server.begin(); }

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

  // when the client sends the first byte, say hello:  if (client) {    if (!gotAMessage) {      Serial.println("We have a new client");      client.println("Hello, client!");       gotAMessage = true;    }

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

DHCP Address PrinterThis sketch uses the DHCP extensions to the Ethernet library to get an IP address via DHCP and print the address obtained using an Arduino Ethernet shield.DHCP is used to assign an IP address when Ethernet.begin(mac) is called. Using DHCP significantly increases the size of a sketch. Using the localIP() function, the assigned IP address is sent out via the serial monitor.Hardware Required

Arduino Ethernet Shield Shield-compatible Arduino board

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

need to change the network settings in the program to correspond to your network.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, your Arduino would be stacked below the Ethernet shield.Code/*  DHCP-based IP printer  This sketch uses the DHCP extensions to the Ethernet library  to get an IP address via DHCP and print the address obtained. using an Arduino Wiznet Ethernet shield.   Circuit: * Ethernet shield attached to pins 10, 11, 12, 13  created 12 April 2011 modified 9 Apr 2012 by Tom Igoe  */

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

// Enter a MAC address for your controller below.// Newer Ethernet shields have a MAC address printed on a sticker on the shieldbyte mac[] = {    0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };

Page 45: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

// 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);  // this check is only needed on the Leonardo:   while (!Serial) {    ; // wait for serial port to connect. Needed for Leonardo only  }

  // start the Ethernet connection:  if (Ethernet.begin(mac) == 0) {    Serial.println("Failed to configure Ethernet using DHCP");    // no point in carrying on, so do nothing forevermore:    for(;;)      ;  }  // print your local IP address:  Serial.print("My IP address: ");  for (byte thisByte = 0; thisByte < 4; thisByte++) {    // print the value of each byte of the IP address:    Serial.print(Ethernet.localIP()[thisByte], DEC);    Serial.print(".");   }  Serial.println();}

void loop() {

}

Telnet ClientThis example connects to a Telnet server using an Ethernet shield. Messages from the server are printed out via the serial port. Messages can be sent to the remote server serially as well. The Serial monitor works well for this purpose.Hardware Required

Arduino Ethernet Shield Shield-compatible Arduino board

Software Required

A telnet server Alternatively, Processing has

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

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

Page 46: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

part of the examples  in the Processing application, available at  http://processing.org/  Circuit: * Ethernet shield attached to pins 10, 11, 12, 13  created 14 Sep 2010 modified 9 Apr 2012 by Tom Igoe  */

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

// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:byte mac[] = {    0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192,168,1,177);

// Enter the IP address of the server you're connecting to:IPAddress server(1,1,1,1); 

// Initialize the Ethernet client library// with the IP address and port of the server // that you want to connect to (port 23 is default for telnet;// if you're using Processing's ChatServer, use  port 10002):EthernetClient client;

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

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 LibraryThe 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.Methodsbegin()

Page 47: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

start the librarybegin(long)start the library and override the default baud rateprintVersion()send the protocol version to the host computerblinkVersion()blink the protocol version on pin 13printFirmwareVersion()send the firmware name and version to the host computersetFirmwareVersion(byte major, byte minor)set the firmware name and version, using the sketch's filename, minus the .pdeSending MessagessendAnalog(byte pin, int value)send an analog messagesendDigitalPorts(byte pin, byte firstPort, byte secondPort)send digital ports as individual bytessendDigitalPortPair(byte pin, int value)send digital ports as one intsendSysex(byte command, byte bytec, byte* bytev)send a command with an arbitrary array of bytessendString(const char* string)send a string to the host computersendString(byte command, const char* string)send a string to the host computer using a custom command typeReceiving Messagesavailable()check to see if there are any incoming messages in the bufferprocessInput()process incoming messages from the buffer, sending the data to any registered callback functionsattach(byte command, callbackFunction myFunction)attach a function to an incoming message typedetach(byte command)detach a function from an incoming message typeCallback FunctionsIn 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);system_resetvoid systemResetCallbackFunction(void);stringvoid stringCallbackFunction(char *myString);sysexvoid sysexCallbackFunction(byte pin, byte byteCount, byte *arrayPointer);Message TypesThese are the various message types that you can attach functions to.ANALOG_MESSAGEthe analog value for a single pinDIGITAL_MESSAGE8-bits of digital pin data (one port)REPORT_ANALOGenable/disable the reporting of analog pinREPORT_DIGITALenable/disable the reporting of a digital portSET_PIN_MODEchange the pin mode between INPUT/OUTPUT/PWM/etc.FIRMATA_STRINGC-style strings, uses stringCallbackFunction for the function typeSYSEX_STARTgeneric, arbitrary length messages (via MIDI SysEx protocol), uses sysexCallbackFunction for the function typeSYSTEM_RESETmessage to reset firmware to its default state, uses systemResetCallbackFunction for the function typeExampleThis 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();

Page 48: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

}

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

GSM libraryThe GSM library is included with Arduino IDE 1.0.4 and later.With the Arduino GSM Shield, this library enables an Arduino board to do most of the operations you can do with a GSM phone: place and receive voice calls, send and receive SMS, and connect to the internet over a GPRS network.The GSM shield has a modem that transfers data from a serial port to the GSM network. The modem executes operations via a series of AT commands. The library abstracts low level communications between the modem and SIM card. It relies on the Software Serial library for communication between the moden and Arduino.Typically, each individual command is part of a larger series necessary to execute a particular function. The library can also receive information and return it to you when necessary.Library structureAs the library enables multiple types of functionality, there are a number of different classes.The GSM class takes care of commands to the radio modem. This handles the connectivity aspects of the shield and registers your system in the GSM infrastructure. All of your GSM/GPRS programs will need to include an object of this class to handle the necessary low level communication.Voice call handling, managed by the GSMVoiceCall class.Send/receive SMS messages, managed by the GSM_SMS class.The GPRSClass is for connecting to the internet.GSMClient includes implementations for a client, similar to the Ethernet and WiFilibraries.

GSMServer includes implementations for a server, similar to the Ethernet and WiFilibraries. NB : A number of network operators do not allow for incoming connections from the public internet, but will allow them from inside their own. Check with your operator to see what restrictions there are on data use.A number of utility classes such as GSMScanner and GSMModemEthernet library compatibilityThe library tries to be as compatible as possible with the current Ethernet library. Porting a program from an Arduino Ethernet or WiFi library to an Arduino with the GSM Shield should be fairly easy. While it is not possible to simply run Ethernet-compatible code on the GSM shield as-is, some minor, library specific, modifications will be necessary, like including the GSM and GPRS specific libraries and getting network configuration settings from your cellular network provider.

GSM classThis class prepares the functions that will communicate with the modem.

GSM begin () shutdown ()

GSMVoiceCall classEnables voice communication through the modem. A microphone and speaker need to be added for full use.

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

GSM_SMS classFacilitates sending and receiving Short Message Service (SMS) messages.

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

Page 49: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

GPRS classThis class is responsible for including the files that are part of the library that involve TCP communication.

GPRS attachGPRS ()

GSMClient classThe client class creates clients that can connect to servers and send and receive data.

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

GSMServer classThe Server class creates servers which can send data to and receive data from connected clients (programs running on other computers or devices).

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

GSMModem classThe GSMModem class facilitates diagnostic communication with the modem.

GSMModem begin () getIMEI ()

GSMScanner classThe GSMScanner class provides diagnostic information about the network and carrier.

GSMScanner begin () getCurrentCarrier () getSignalStrength () readNetworks ()

GSMPIN classThe GSMPIN class has utilities for communicating with the SIM card.

GSMPIN begin () isPIN () checkPIN () checkPUK () changePIN () switchPIN () checkReg ()

getPINUsed () setPINUsed ()

GSMBand classThe GSMBand class provides information about the frequency band the modem connects to. There are also methods for setting the band.

GSMBand begin () getBand () setBand ()

GSM constructorDescriptionGSM is the base class for all GSM based functions.SyntaxGSM GSMAccessGSM GSMAccess(debug)Parametersdebug: 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 instanceGSM 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_READY){      notConnected = false;      Serial.println("Connected to network");    }    else    {      Serial.println("Not connected");      delay(1000);

Page 50: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    }  }}

void loop(){  // Nothing here} 

begin()DescriptionConnects to the GSM network identified on the SIM card.Syntaxgsm.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) modeReturnschar : 0 if asynchronous. If synchronous, returns status : ERROR, IDLE, CONNECTING, GSM_READY, GPRS_READY, TRANSPARENT_CONNECTEDExample#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()DescriptionDisconnects from the GSM network identified on the SIM card by powering the modem off.Syntaxgsm.shutdown()ParametersnoneReturnsboolean : 0 while executing, 1 when successfulExample#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");

Page 51: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  gsm.shutdown();  Serial.println("GSM terminated");

}

void loop(){}

GSMVoiceCall constructorDescriptionGSMVoiceCall is the base class for all GSM functions relating to receiving and making voice calls.

GSM : GSMVoiceCall classgetVoiceCallStatus()DescriptionReturns status of the voice call.Syntaxvoice.getVoiceCallStatus()ParametersnoneReturnschar : IDLE_CALL, CALLING, RECEIVINGCALL, TALKINGExample

// libraries#include <GSM.h>

// PIN Number#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSMVoiceCall vcs;

char numtel[20];           // buffer for the incoming 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_READY)      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);

Page 52: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

GSM : GSMVoiceCall classready()DescriptionReports if the previous voice command has executed successfullySyntaxvoice.ready()ParametersnoneReturnsintIn 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.

GSM : GSMVoiceCall classvoiceCall()DescriptionPlaces 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.Syntaxvoice.voiceCall(number)Parameters

number : char array. The number to call.ReturnsintIn 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 instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSMVoiceCall vcs;

String remoteNumber = "";  // the number you will callchar charbuffer[20];

void setup(){

  // initialize serial communications  Serial.begin(9600); 

  Serial.println("Make Voice Call");

  // connection state  boolean notConnected = true;

  // Start GSM shield  // If your SIM has PIN, pass it as a parameter of begin() in quotes  while(notConnected)  {  if(gsmAccess.begin(PINNUMBER)==GSM_READY)      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)      {        // 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

Page 53: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.getvoiceCallStatus()==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()DescriptionAccepts an incoming voice call. The method returns are different depending on the modem mode (asynchronous or synchronous), see below for details.Syntaxvoice.answerCall()ParametersnoneReturnsintIn 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 instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSMVoiceCall vcs;

char numtel[20];           // buffer for the incoming 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_READY)      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

Page 54: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

      vcs.retrieveCallingNumber(numtel, 20);

      // Print the calling number      Serial.print("Number:");      Serial.println(numtel);

      // Answer the call, establish the call      vcs.answerCall();               break;

    case TALKING:  // In this case the call would be established

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

hangCall()DescriptionHang 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.Syntaxvoice.hangCall()ParametersnoneReturnsintIn 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 instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSMVoiceCall vcs;

char numtel[20];           // buffer for the incoming 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_READY)      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);

Page 55: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

retrieveCallingNumber()DescriptionRetrieves the calling number, and stores it.Syntaxvoice.retrieveCallingNumber(number, size)Parameters

number : char array to hold the number size : the size of the array

ReturnsintIn 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 instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSMVoiceCall vcs;

char numtel[20];           // buffer for the incoming 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_READY)      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')

Page 56: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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

beginSMS()DescriptionIdentifies the telephone number to send an SMS message to.SyntaxSMS.beginSMS(number)Parametersnumber : char array, the phone number to send the SMS toReturnsint 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 instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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_READY)      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++;      }

Page 57: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    }  }}

ready()DescriptionGets the status if the last GSMSMS command.SyntaxSMS.ready()ParametersnoneReturnsint 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()DescriptionTells the modem that the SMS message is complete and sends it.SyntaxSMS.endSMS()ParametersnoneReturnsint 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 instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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_READY)      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();

Page 58: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

available()DescriptionChecks 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.SyntaxSMS.available()ParametersnoneReturnsint : the number of characters in the messageExample#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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;

  // Start GSM shield  // If your SIM has PIN, pass it as a parameter of begin() in quotes  while(notConnected)  {  if(gsmAccess.begin(PINNUMBER)==GSM_READY)      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);

    Serial.println("\nEND OF MESSAGE");

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

  delay(1000);

}

remoteNumber()DescriptionRetrieves the phone number an from an incoming SMS message and stores it in a named array.SyntaxSMS.remoteNumber(number, size)Parameters

number : char array, a named array that will hold the sender's number

size : int, the size of the arrayReturnsint In asynchronous mode,

Page 59: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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 ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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;

  // Start GSM shield  // If your SIM has PIN, pass it as a parameter of begin() in quotes  while(notConnected)  {  if(gsmAccess.begin(PINNUMBER)==GSM_READY)      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);

    Serial.println("\nEND OF MESSAGE");

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

  delay(1000);

}

read()DescriptionReads a byte from an SMS message. read() inherits from the Stream utility class.SyntaxSMS.read()ParametersnoneReturnsint - the first byte of incoming serial data available (or -1 if no data is available)Example#include <GSM.h>

// PIN Number#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_SMS sms;

char remoteNumber[20];  // Holds the emitting number

void setup() {  // initialize serial communications

Page 60: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  Serial.begin(9600); 

  Serial.println("SMS Messages Receiver");

  // connection state  boolean notConnected = true;

  // Start GSM shield  // If your SIM has PIN, pass it as a parameter of begin() in quotes  while(notConnected)  {  if(gsmAccess.begin(PINNUMBER)==GSM_READY)      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);

    Serial.println("\nEND OF MESSAGE");

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

  delay(1000);

}

write()DescriptionWrites a character to a SMS message.SyntaxSMS.write(val)Parametersval: a character to send in the messageReturnsbyte - write() will return the number of bytes written, though reading that number is optionalExample#include <GSM.h>

#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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_READY)      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

Page 61: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

to send sms  readSerial(remoteNumber);  Serial.println(remoteNumber);

  // sms text  Serial.print("Now, enter SMS content: ");  char txtMsg[200];  readSerial(txtMsg);  Serial.println("SENDING");  Serial.println();  Serial.println("Message:");  Serial.println(txtMsg);

  // send the message  sms.beginSMS(remoteNumber);  sms.print(txtMsg);  sms.endSMS();   Serial.println("\nCOMPLETE!\n");}

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

peek()DescriptionReturns 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.SyntaxSMS.peek()Parametersnone

Returnsint - 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>

// PIN Number#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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;

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

  Serial.println("GSM initialized");

Page 62: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

}

flush()Descriptionflush() clears the modem memory of any sent messages once all outgoing characters have been sent. flush() inherits from the Stream utility class.SyntaxSMS.flush()ParametersnoneReturnsnoneExample/*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 ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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;

  // Start GSM shield  // If your SIM has PIN, pass it as a parameter of begin() in quotes  while(notConnected)  {  if(gsmAccess.begin(PINNUMBER)==GSM_READY)      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())  {

Page 63: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

}

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

attachGPRS()DescriptionConnects 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.

Syntaxgrps.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 APNReturnschar array : ERROR, IDLE, CONNECTING, GSM_READY, GPRS_READY, TRANSPARENT_CONNECTEDExample#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 instanceGPRS gprs;GSM gsmAccess;     // include a 'true' parameter for debug enabledGSMServer server(80); // port 80 (http default)

// timeoutconst 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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, 

Page 64: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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; analogChannel < 6; analogChannel++) {            client.print("analog input ");            client.print(analogChannel);            client.print(" is ");            client.print(analogRead(analogChannel));            client.println("<br />");       

          }          client.println("</html>");          //necessary delay          delay(1000);          client.stop();        }      }    }  }}

GSM : Client classClientDescriptionClient 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.

ready()DescriptionGets the status of the last commandSyntaxclient.ready()ParametersnoneReturnsIn 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()DescriptionConnects to a specified IP address and port. The return value indicates success or failure.Syntaxclient.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)Returnsboolean : Returns true if the connection succeeds, false if not.Example/*  Web client

Page 65: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

 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/GSMExamplesWebClient

 */

// 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 instanceGSMClient 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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))

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

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

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

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

  // if the server's disconnected, stop the client:  if (!client.available() && !client.connected())  {    Serial.println();    Serial.println("disconnecting.");    client.stop();

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

beginWrite()DescriptionTells the client to start writing to the server it is connected to.Syntaxclient.beginWrite()Parametersnone

Page 66: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Returnsnone

write()DescriptionWrite data to the server the client is connected to.Syntaxclient.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)

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

endWrite()DescriptionStops writing data to a serverSyntaxclient.endWrite()ParametersnoneReturnsnone

connected()DescriptionReturns whether or not the client is connected. A client is considered connected if the connection has been closed but there is still unread data.Syntaxclient.connected()ParametersnoneReturnsboolean - 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/GSMExamplesWebClient

 */

// 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 instanceGSMClient 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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))      notConnected = false;    else    {      Serial.println("Not connected");

Page 67: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

read()DescriptionRead 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.Syntaxclient.read()Parametersnone

Returnsint - 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/GSMExamplesWebClient

 */

// 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 instanceGSMClient 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)

Page 68: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  {  if((gsmAccess.begin(PINNUMBER)==GSM_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, 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(;;)      ;  }}

available()

DescriptionReturns 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.Syntaxclient.available()ParametersnoneReturnsThe 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

 http://arduino.cc/en/Tutorial/GSMExamplesWebClient

 */

// 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 instanceGSMClient 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

Page 69: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, 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(;;)      ;  }}

peek()DescriptionReturns 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.Syntaxclient.peek()ParametersnoneReturnsint - the next byte in an incoming message.

flush()DescriptionDiscards any bytes that have been written to the client but not yet read.flush() inherits from the Stream utility class.Syntaxclient.flush()ParametersnoneReturnsnone

stop()DescriptionDisconnects from the serverSyntaxclient.stop()ParametersnoneReturnsnoneExample/*  Web client

 This sketch connects to a website through a GSM shield. Specifically,

Page 70: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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/GSMExamplesWebClient

 */

// 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 instanceGSMClient 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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, 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(;;)      ;  }}

ServerDescriptionServer 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.SyntaxGSMServer server(port);

Page 71: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Parametersport: int, the port the server will accept connections on. The default web port is 80.

ready()DescriptionGet last command status to the serverSyntaxserver.ready()ParametersnoneReturnsint - 0 if last command is still executing, 1 if success, >1 if an error.

beginWrite()DescriptionBegins writing to connected clients.Syntaxserver.beginWrite()ParametersnoneReturnsnone

write()DescriptionWrite data to all the clients connected to a server.Syntaxserver.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)

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

endWrite()DescriptionTells the server to stop writing to connected clients.

Syntaxserver.endWrite()ParametersnoneReturnsnone

read()DescriptionRead the next byte received from an attached client (after the last call to read()).read() inherits from the Stream utility class.Syntaxserver.read()ParametersnoneReturnsint - The next byte (or character), or -1 if none is available.

available()DescriptionListens for incoming clientsSyntaxserver.available()ParametersnoneReturnsint : the number of connected clients

GSMModem ConstructorDescriptionGSMModem 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 HomeCorrections, 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.

Page 72: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Code samples in the reference are released into the public domain.

begin()DescriptionChecks the modem status, and restarts it. Call this before GSMModem.getIMEI().Syntaxmodem.begin()ParametersnoneReturnsint : returns 1 if modem is OK, otherwise returns an error.

getIMEI()DescriptionRetrieves the modem's IMEI number. Call this after GSMModem.begin().Syntaxmodem.getIMEI()ParametersnoneReturnsString : the modem's IMEI numberExample// libraries#include <GSM.h>

// modem verification objectGSMModem modem;

// IMEI variableString IMEI = "";

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

  // start modem test (reset and check response)  Serial.print("Starting modem test...");  if(modem.begin())     Serial.println("modem.begin() succeeded");  else    Serial.println("ERROR, no modem answer.");}

void loop(){  // get modem IMEI  Serial.print("Checking IMEI...");  IMEI = modem.getIMEI();

  // check IMEI response  if(IMEI != NULL)  {    // show IMEI in serial monitor    Serial.println("Modem's IMEI: " + IMEI);    // reset modem to check booting:    Serial.print("Reseting modem...");    modem.begin();    // get and check IMEI one more time    if(modem.getIMEI() != NULL)    {      Serial.println("Modem is functoning properly");    }    else    {      Serial.println("Error: getIMEI() failed after modem.begin()");    }  }  else  {    Serial.println("Error: Could not get IMEI");  }  // do nothing:  while(true);}

GSMScanner ConstructorDescriptionGSMScanner is the base class for calls that have specific diagnostic functionality relating to scanning for available networks. It is not called directly, but invoked whenever you use a function that relies on it.

begin()DescriptionResets modem hardware.Syntaxscanner.begin()ParametersnoneReturnsint : returns 1 if modem is OK, otherwise returns an error.

getCurrentCarrier()DescriptionGets and returns the name of the current network carrier.Syntaxscanner.getCurrentCarrier()

Page 73: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

ParametersnoneReturnsString : name of the current network carrier

getSignalStrength()DescriptionGets and returns the strength of the signal of the network the modem is attached to.Syntaxscanner.getSignalStrength()ParametersnoneReturnsString : signal strength in 0-31 scale. 31 means power > 51dBm. 99=not detectable

readNetworks()DescriptionSearches for available carriers, and returns a list of them.Syntaxscanner.readNetworks()ParametersnoneReturnsString : A string with list of networks available

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

begin()DescriptionChecks the modem status, and restarts it.SyntaxGSMPIN.begin()Parametersnone

Returnsint : returns 1 if modem is OK, otherwise returns an error.

isPIN()DescriptionChecks the SIM card to see if it is locked with a PIN.Syntaxpin.isPIN()ParametersnoneReturnsint : 0 if PIN lock is off, 1 if PIN lock is on, -1 if PUK lock is on, -2 if error exists.

checkPIN()DescriptionQueries the SIM card with a PIN number to see if it is valid.Syntaxpin.checkPIN(PIN)ParametersPIN : String with the PIN number to checkReturnsint : Returns 0 if the PIN is valid, returns -1 if it is not.

checkPUK()DescriptionCheck the SIM if PUK code is correct and establish new PIN code.Syntaxpin.checkPUK(puk, pin)Parameters

puk : String with the PUK number to check

pin : String with the PIN number to checkReturnsint : Returns 0 if successful, -1 if it is not.

changePIN()DescriptionChanges the PIN number of a SIM, after verifying the existing one.

Page 74: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Syntaxpin.changePIN(oldPIN, newPIN)ParametersoldPIN : String with the existing PIN number newPIN : String with the desired PIN numberReturnsnone

switchPIN()DescriptionChange PIN lock status.Syntaxpin.switchPIN(pin)Parameterspin : String with the existing PIN numberReturnsnone

checkReg()DescriptionCheck if modem was registered in GSM/GPRS networkSyntaxpin.checkReg()ParametersReturnsint : 0 if modem was registered, 1 if modem was registered in roaming, -1 if error exists

getPinUsed()DescriptionCheck if PIN lock is used.Syntaxpin.getPinUsed()ParametersReturnsboolean : TRUE id locked, FALSE if not

setPinUsed()DescriptionSet PIN lock status.Syntaxpin.setPinUsed(used)Parametersused : boolean, TRUE to lock the PIN, FALSE to unlock.

Returnsnone

GSMBand ConstructorDescriptionGSMBand 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()DescriptionChecks the modem status, and restarts it.Syntaxband.begin()ParametersnoneReturnsint : returns 1 if modem is OK, otherwise returns an error.

getBand()DescriptionGets and returns the frequency band the modem is currently connected to. Checkhttp://www.worldtimezone.com/gsm.html for general GSM band information. Typical regional configurations are :

Europe, Africa, Middle East: E-GSM(900)+DCS(1800)

USA, Canada, South America: GSM(850)+PCS(1900)

Mexico: PCS(1900) Brazil: GSM(850)+E-

GSM(900)+DCS(1800)+PCS(1900)Syntaxband.getBand()ParametersnoneReturnsString : name of the frequency band the modem connects to

GSM_MODE_UNDEFINED GSM_MODE_EGSM GSM_MODE_DCS GSM_MODE_PCS

Page 75: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

GSM_MODE_EGSM_DCS GSM_MODE_GSM850_PCS GSM_MODE_GSM850_EGSM_DCS_

PCS

setBand()DescriptionSets the frequency band the modem connects to. Check http://www.worldtimezone.com/gsm.html for general GSM band information. Typical regional configurations are :

Europe, Africa, Middle East: E-GSM(900)+DCS(1800)

USA, Canada, South America: GSM(850)+PCS(1900)

Mexico: PCS(1900) Brazil: GSM(850)+E-

GSM(900)+DCS(1800)+PCS(1900)Syntaxband.setBand(type)Parameterstype : 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_

PCSReturnsboolean : returns true if the process is successful, false if it is not

Make Voice CallThis 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 cardCircuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>SIM cards may have a PIN number that unlocks their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""Initialize instances of the classes you're going to use. You're going to need both the GSM and GSMVoiceCall class.GSM gsmAccess; GSMVoiceCall vcs;

[Get Code]Create some variables to store the phone number you want to call :String remoteNumber = "";char charbuffer[20];

[Get Code]

Page 76: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

In setup, open a serial connection to the computer. You'll use this to send a phone number to the Arduino. After opening the connection, send a message to the Serial Monitor indicating the sketch has started.void setup(){

  Serial.begin(9600);   Serial.println("Make Voice Call");

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

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

[Get Code]Finish setup with some information to the serial monitor.Serial.println("GSM initialized.");  Serial.println("Enter phone number to call.");}

[Get Code]The loop will accept incoming bytes from the serial monitor and connect your voice call.First, check the serial buffer to see if there is any information waiting to be read. If there is, store it in a local variable :

void loop(){  while (Serial.available() > 0)  {    char inChar = Serial.read();

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

[Get Code]Print out the number you're calling to the serial monitor.Serial.print("Calling to : ");        Serial.println(remoteNumber);        Serial.println();

[Get Code]The number to call will be been stored in the String named remoteNumber. The voiceCall() function requires a chararray. Copy the string to the array named charbuffer.remoteNumber.toCharArray(charbuffer, 20);To place the call, use vcs.voiceCall(), passing it the number you wish to reach. voiceCall() returns the status of the call; a 1 means it is connected. You can check the status of the connection with getvoiceCallStatus().To disconnect your call, send a newline character to trigger hangCall().if(vcs.voiceCall(charbuffer))        {          Serial.println("Call Established. Enter line to end");          while(Serial.read()!='\n' && (vcs.getvoiceCallStatus()==TALKING));    

          vcs.hangCall();        }

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

[Get Code]

Page 77: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

If the number you entered in the serial monitor is longer than 20 digits, clear the remoteNumber String and start again :else      {        Serial.println("That's too long for a phone number. I'm forgetting it");         remoteNumber = "";      }    }

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

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

 */

// libraries#include <GSM.h>

// PIN Number#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSMVoiceCall vcs;

String remoteNumber = "";  // the number you will callchar charbuffer[20];

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

Page 78: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.getvoiceCallStatus()==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;    }  } }

Receive Voice CallThis sketch receives a voice call from an Arduino with a connected GSM shield. Once connected, it shows the number that is calling, and hangs up. You'll need to attach a speaker and

microphone to hear the connected call and send your voice.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

Shield Microphone and speaker attached to

the GSM shield SIM card

Circuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>SIM cards may have a PIN number that unlocks their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""

Page 79: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Initialize instances of the classes you're going to use. You're going to need both the GSM and GSMVoiceCall class.GSM gsmAccess; GSMVoiceCall vcs;

[Get Code]Create a char array to store the incoming number :char numtel[20];

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

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

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

[Get Code]To ensure the modem is ready to accept incoming calls, use the hangCall() functionvcs.hangCall();Finish setup with some information to the serial monitor.

Serial.println("GSM initialized.");  Serial.println("Awaiting call.");}

[Get Code]In loop, use a switch statement to control the flow of the program. getvoiceCallStatus() will return its state when it is called.void loop(){  switch (vcs.getvoiceCallStatus())   {

[Get Code]If getvoiceCallStatus() returns IDLE_CALL, there is nothing happening.case IDLE_CALL: 

      break;[Get Code]

If getvoiceCallStatus() returns RECEIVINGCALL, someone is calling you. Use retrieveCallingNumber() to store the incoming number to the numtel array you created, and print it to the serial monitor.Use answerCall() to initiate the voice conection with the caller.case RECEIVINGCALL:

      Serial.println("RECEIVING CALL");

      vcs.retrieveCallingNumber(numtel, 20);

      Serial.print("Number:");      Serial.println(numtel);

      vcs.answerCall();               break;

[Get Code]Once you have answered the call, getvoiceCallStatus() will return TALKING. The sketch will wait for a newline character to trigger hangCall() and terminate the connection.Close the switch statement.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]

Page 80: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Add a small delay before continuing with the loop:delay(1000);}

[Get Code]Once your code is uploaded, open the serial monitor. Make sure the serial monitor is set to only send a newline character on return./* Receive Voice Call

 This sketch, for the Arduino GSM shield, receives voice calls,  displays the calling number, waits a few seconds and gently hangs,

 Circuit: * GSM shield  * Voice circuit.  With no voice circuit the call will send nor receive any sound

 created Mar 2012 by Javier Zorzano

 This example is in the public domain. */

// libraries#include <GSM.h>

// PIN Number#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSMVoiceCall vcs;

char numtel[20];           // buffer for the incoming 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_REA

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

Page 81: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Send SMSThis sketch send a SMS message from an Arduino with a connected GSM shield. using the serial monitor, you'll enter the number to connect with, and the message to send.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card

Circuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""

Initialize instances of the classes you're going to use. You're going to need both the GSM and GSM_SMS class.GSM gsmAccess; GSM_SMS sms;

[Get Code]In setup, open a serial connection to the computer. After opening the connection, send a message indicating the sketch has started.void setup(){  Serial.begin(9600);   Serial.println("SMS Messages Sender");

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

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

[Get Code]Finish setup with some information to the serial monitor.Serial.println("GSM initialized.");}

[Get Code]Create a function named readSerial of type int. You'll use this to iterate through input from the serial monitor, storing the number you wish to send an SMS to, and the message you'll be sending.

Page 82: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

It should accept a char array as an argument.int readSerial(char result[]){

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

[Get Code]As long as there is serial information available, read the data into a variable named inChar.while (Serial.available() > 0)    {      char inChar = Serial.read();

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

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

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

[Get Code]

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

[Get Code]Call sms.beginSMS() and pass it remoteNumber to start sending the message, sms.print() to send the message, andsms.endSMS() to complete the process. Print out some diagnostic information and close the loop. Your message is on its way!Serial.println("SENDING");  Serial.println();  Serial.println("Message:");  Serial.println(txtMsg);

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

[Get Code]Once your code is uploaded, open the serial monitor. Make sure the serial monitor is set to only send a newline character on return. When prompted to enter the number you wish to call, enter the digits and press return. You'll then be asked to enter your message. Once you've typed that, press return again to send it./*SMS sender

 This sketch, for the Arduino GSM shield,sends an SMS message   that you send it through the serial monitor. To make it work,  open the serial monitor, and when you see the READY message,   type a message to send. Make sure the serial monitor is set  to send a newline when you press return.

 Circuit: * GSM shield 

 created 25 Feb 2012 by Tom Igoe

 This example is in the public domain. */

Page 83: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

// libraries#include <GSM.h>

#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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_READY)      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++;      }    }  }}

Receive SMSThis 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

Page 84: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""Initialize instances of the classes you're going to use. You're going to need both the GSM and GSM_SMS class.GSM gsmAccess; GSM_SMS sms;

[Get Code]Create a char array to hold the number that is sending the message :char remoteNumber[20];In setup, open a serial connection to the computer. After opening the connection, send a message indicating the sketch has started.

void setup(){  Serial.begin(9600);   Serial.println("SMS Messages Receiver");

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

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

[Get Code]Finish setup with some information to the serial monitor.Serial.println("GSM initialized.");  Serial.println("Waiting for messages");}

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

Page 85: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

void loop() {  char c;  if (sms.available())  {

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

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

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

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

[Get Code]Add a brief delay and close the loop.delay(1000);}

[Get Code]Once your code is uploaded, open the serial monitor. With a phone, or other SMS enabled service, send a SMS to

the number of your SIM. You should see the message print out on screen when it is received./*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 ""

// initialize the library instanceGSM gsmAccess; // include a 'true' parameter for debug enabledGSM_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;

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

  Serial.println("GSM initialized");  Serial.println("Waiting for messages");

Page 86: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

}

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

}

GSM Web ClientThis sketch connects an Arduino to the Arduino homepage, http://arduino.cc, through a GSM shield. It then prints the content of the page through the serial monitor.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card with a data connection

Circuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""Define a number of constants that contain information about the GPRS network you're going to connect to. You'll need the Access Point Name (APN), login, and password. To obtain this information, contact your network provider for the most up to date information. This page has some information about various carrier settings, but it may not be current.

Page 87: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

#define GPRS_APN       "GPRS_APN" #define GPRS_LOGIN     "login"#define GPRS_PASSWORD  "password"

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

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

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

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

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

DY)      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))      notConnected = false;    else    {      Serial.println("Not connected");      delay(1000);    }  }

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

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

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

[Get Code]If the server disconnects, which it will typically do once it has completed the HTTP request, stop the client locally and close the loop.if (!client.available() && !client.connected())  {    Serial.println();    Serial.println("disconnecting.");    client.stop();

Page 88: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

[Get Code]Once your code is uploaded, open the serial monitor. You should see the HTML of http://arduino.cc print out on screen when it is received./* GSM Web client

 This sketch connects to a website using a GSM shield.

 Circuit: * GSM shield attached

 created 8 Mar 2012 by Tom Igoe */

// libraries#include <GSM.h>

// 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 instanceGSMClient 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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))      notConnected = false;    else    {      Serial.println("Not connected");      delay(1000);    }  }

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

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

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

  // if the server's disconnected, stop the client:  if (!client.available() && !client.connected())  {    Serial.println();    Serial.println("disconnecting.");    client.stop();

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

GSM Web Server

Page 89: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

This sketch turns the Arduino with a GSM shield and a data enabled SIM card into a web server. When the Arduino receives a request from a connected client, it sends back the value of analog inputs 0-5.Not all network operators allow incoming data requests from outside their network. This means you can create a web server with the GSM shield, but you may not be able to connect to it from the public internet; only from another data enabled device from the same provider on the same network. You should check with your provider to see what specific policies they have in place regarding incoming data connections.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card with a data connection (optional) 6 potentiometers or other

analog inputs attached to A0-A5Circuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""Define a number of constants that contain information about the GPRS network you're going to connect to. You'll need the Access Point Name (APN), login, and password. To obtain this information, contact your network provider for the most up to date information. This page has some information about various carrier settings, but it may not be current.

Page 90: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

#define GPRS_APN       "GPRS_APN" #define GPRS_LOGIN     "login"#define GPRS_PASSWORD  "password"

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

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

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

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

(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))      notConnected = false;    else    {      Serial.println("Not connected");      delay(1000);    }  }

[Get Code]Start the server using server.begin(). You can request the server's IP address with grps.getIPAddress() and end the setup.server.begin();

  IPAddress LocalIP = gprs.getIPAddress();  Serial.println("Server IP address=");  Serial.println(LocalIP);}

[Get Code]In loop, create an instance of GSMClient and check if there are any active connectionsvoid loop() {  GSMClient client = server.available();

  if (client)  {

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

[Get Code]Once the request has been read, start to send a standard HTTP response header with client.print() andclient.println().if (sendResponse)       {          client.println("HTTP/1.1 200 OK");          client.println("Content-Type: text/html");          client.println();          client.println("<html>");

Page 91: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

[Get Code]Read through the analog inputs and send the values to the client.for (int analogChannel = 0; analogChannel < 6; analogChannel++) {            client.print("analog input ");            client.print(analogChannel);            client.print(" is ");            client.print(analogRead(analogChannel));            client.println("<br />");                 }

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

[Get Code]Once your code is uploaded, open the serial monitor. Once the IP address is printed to the serial monitor, enter it into a web browser. You should see a webpage that reports the analog input values on each the Arduino's six inputs.if you cannot connect to the IP address, make sure your network operator enables incoming traffic./* GSM Web Server

 A simple web server that shows the value of the analog input pins. using a GSM shield.

 Circuit: * GSM shield attached * Analog inputs attached to pins A0 through A5 (optional)

 created 8 Mar 2012 by Tom Igoe */

// 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 instanceGPRS gprs;GSM gsmAccess;     // include a 'true' parameter for debug enabledGSMServer server(80); // port 80 (http default)

// timeoutconst 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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, 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();

Page 92: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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; analogChannel < 6; analogChannel++) {            client.print("analog input ");            client.print(analogChannel);            client.print(" is ");            client.print(analogRead(analogChannel));            client.println("<br />");                 }          client.println("</html>");          //necessary delay          delay(1000);          client.stop();        }      }    }  }}

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

To use a data connection with the GSM shield, you'll need your provider's Access Point Name (APN), login, and password. To obtain this information, contact the network provider for the most up to date information. This page has some information about various carrier settings, but it may not be current.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card with a data connection Analog sensor attached to A0

Software Required xively.com account xively.com feed  that accepts two data

itemsCircuit

Page 93: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>Declare the various settings for your Xively account; your API key, feed ID, and project name (the user agent).#define APIKEY         "YOUR API KEY GOES HERE"  #define FEEDID         00000    #define USERAGENT      "My Project"

[Get Code]SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""Define a number of constants that contain information about the GPRS network you're going to connect to. You'll need the Access Point Name (APN), login, and password. To obtain this information, contact your network provider for the most up to date information. This page has some information about various carrier settings, but it may not be current.#define GPRS_APN       "GPRS_APN" #define GPRS_LOGIN     "login"#define GPRS_PASSWORD  "password"

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

[Get Code]Create some variables to store information you're going to need in the sketch; a char array to hold the URL, and some variables for setting timing intervals.char server[] = "api.xively.com";

unsigned long lastConnectionTime = 0; boolean lastConnected = false;const unsigned long postingInterval = 10*1000;

[Get Code]In setup, open a serial connection to the computer.void setup(){  Serial.begin(9600);

[Get Code]

Create a local variable to track the connection status. You'll use this to keep the sketch from starting until the SIM is connected to the network :boolean notConnected = true;

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

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

[Get Code]Check to see if there is a successful connection to the serverif (client.connect(server, 80))  {    Serial.println("connecting...");

[Get Code]

Page 94: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

When connected, send a HTTP PUT request with the information about your feedclient.print("PUT /v2/feeds/");    client.print(FEEDID);    client.println(".csv HTTP/1.1");    client.print("Host: api.xively.com\n");    client.print("X-ApiKey: ");    client.println(APIKEY);    client.print("User-Agent: ");    client.println(USERAGENT);    client.print("Content-Length: ");

[Get Code]You'll need to calculate the length of the data you're sending. The length will be 8 bytes for the term "sensor1," plus the number of digits of the data. You'll create a new function named getLength() in a moment to handle this information. Once calculated, send the length to the server, and the last pieces of the PUT.Last, send the data to the server.int thisLength = 8 + getLength(thisData);    client.println(thisLength);

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

    client.print("sensor1,");    client.println(thisData); }

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

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

[Get Code]Create another function, named getLength(), for determining the length of the data being sent in bytes.

int getLength(int someValue){

[Get Code]Create a variable named digits to hold the number of bytes. You know that there will always be at least one digit being sent.To find the total number of digits to send, continually divide the value by ten, adding one to the digit count each time you divide, until you reach 0.int digits = 1;

  int dividend = someValue /10;  while (dividend > 0)  {    dividend = dividend /10;    digits++;  }

[Get Code]Return the number of digits and close the function.return digits;}

[Get Code]Inside loop, read the value from the analog sensor and store it in a local variablevoid loop(){  int sensorReading = analogRead(A0);

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

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

[Get Code]If there is no connection, and ten seconds have passed since the last connection, or connection attempt, then connect again and send dataif(!client.connected() && ((millis() - lastConnectionTime) > postingInterval))  {

Page 95: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  sendData(sensorReading);  }

[Get Code]Store the state of the connection for next time through loop() and close it up.lastConnected = client.connected();}

[Get Code]Once your code is uploaded, open the serial monitor for debugging, and check your xively.com feed to see updates./* GSM Xively client  This sketch connects an analog sensor to Xively (http://www.xively.com) using a Telefonica GSM/GPRS shield.

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

// 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.comchar server[] = "api.xively.com";      // name address for xively API

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in millisecondsboolean lastConnected = false;                  // state of the connection last time through the main loopconst 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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))      notConnected = false;    else    {      Serial.println("Not connected");      delay(1000);    }  }}

void loop(){    // read the analog sensor:

Page 96: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  int sensorReading = analogRead(A0);   

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

  // if there's no net connection, but there was one last time  // through the loop, then stop the client:  if (!client.connected() && lastConnected)  {    client.stop();  }    // if you're not connected, and ten seconds have passed since  // your last connection, then connect again and send data:  if(!client.connected() && ((millis() - lastConnectionTime) > postingInterval))  {  sendData(sensorReading);  }    // store the state of the connection for next time through  // the loop:  lastConnected = client.connected();}

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

    // calculate the length of the sensor reading in bytes:    // 8 bytes for "sensor1," + number of digits of

the data:    int thisLength = 8 + getLength(thisData);    client.println(thisLength);

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

/*  This method calculates the number of digits in the  sensor reading.  Since each digit of the ASCII decimal  representation is a byte, the number of digits equals  the number of bytes.*/int getLength(int someValue){  // there's at least one byte:  int digits = 1;    // continually divide the value by ten,   // adding one to the digit count for each  // time you divide, until you're at 0:  int dividend = someValue /10;  while (dividend > 0)  {    dividend = dividend /10;    digits++;  }    // return the number of digits:  return digits;}

GSM Xively Client StringThis example shows you how to answer a HTTP request using a GSM shield attached to an Arduino. Specifically, it connects to xively.com, a

Page 97: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

free datalogging site and sends data as a string. The example requires that you set up a xively.com account, as well as a xively feed (for more information on setting up an input feed, please click here). Your GSM shield will then connect to that feed and upload sensor data.To use a data connection with the GSM shield, you'll need your provider's Access Point Name (APN), login, and password. To obtain this information, contact the network provider for the most up to date information. This page has some information about various carrier settings, but it may not be current.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card with a data connection Analog sensors attached to A0 and A1

Software Required xively.com account xively.com feed  that accepts two data

itemsCircuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>Declare the various settings for your xively account; your API key, feed ID, and project name (the user agent).#define APIKEY         "YOUR API KEY GOES HERE"  #define FEEDID         00000    #define USERAGENT      "My Project"

[Get Code]SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""Define a number of constants that contain information about the GPRS network you're going to connect to. You'll need the Access Point Name (APN), login, and password. To obtain

Page 98: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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

[Get Code]Create some variables to store information you're going to need in the sketch; a char array to hold the URL, and some variables for setting timing intervals.char server[] = "api.xively.com";

unsigned long lastConnectionTime = 0; boolean lastConnected = false;const unsigned long postingInterval = 10*1000;

[Get Code]In setup, open a serial connection to the computer.void setup(){  Serial.begin(9600);

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

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

set the notConnected variable to true or false. Once connected, sned a status message to the serial monitor and close setup.while(notConnected)  {  if(gsmAccess.begin(PINNUMBER)==GSM_READY)      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))      notConnected = false;    else    {      Serial.println("Not connected");      delay(1000);    }  }  Serial.println("Connected to GPRS network");}

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

[Get Code]Check to see if there is a successful connection to the serverif (client.connect(server, 80))  {    Serial.println("connecting...");

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

[Get Code]Once the length has been sent, pass on the last pieces of the PUT request, and the data to the server.

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

Page 99: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    client.println();

    client.println(thisData); }

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

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

[Get Code]Inside loop, read the value from A0 and store it in a local variablevoid loop(){  int sensorReading = analogRead(A0);

[Get Code]Convert the data to a string and prefix it with "sensor1, "String dataString = "sensor1,";  dataString += sensorReading;

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

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

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

    client.stop();  }

[Get Code]If there is no connection, and ten seconds have passed since the last connection, or connection attempt, then connect again and send dataif(!client.connected() && ((millis() - lastConnectionTime) > postingInterval))  {  sendData(sensorReading);  }

[Get Code]Store the state of the connection for next time through loop() and close it up.lastConnected = client.connected();}

[Get Code]Once your code is uploaded, open the serial monitor for debugging, and check your xively.com feed to see updates./* Xively client with Strings  This sketch connects two analog sensors to Xively (http://www.xively.com) through a Telefonica GSM/GPRS shield.  This example has been updated to use version 2.0 of the Xively.com API.  To make it work, create a feed with two datastreams, and give them the IDs sensor1 and sensor2. Or change the code below to match your feed.  This example uses the String library, which is part of the Arduino core from version 0019.    Circuit: * Analog sensors attached to A0 and A1 * GSM shield attached to an Arduino * SIM card with a data plan  created 8 March 2012 by Tom Igoe and adapted for GSM shield by David Del Peral  This code is in the public domain.  */

// Include the GSM library#include <GSM.h>

// Xively login information#define APIKEY         "YOUR API KEY GOES HERE"  // replace your xively api key here#define FEEDID         00000                     // replace your feed ID

Page 100: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

#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 instanceGSMClient 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.comchar server[] = "api.xively.com";       // name address for Xively API

unsigned long lastConnectionTime = 0;           // last time you connected to the server, in millisecondsboolean lastConnected = false;                  // state of the connection last time through the main loopconst 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_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))      notConnected = false;

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

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

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 there's incoming data from the net connection.  // send it out the serial port.  This is for debugging  // purposes only  if (client.available())  {    char c = client.read();    Serial.print(c);  }

  // if there's no net connection, but there was one last time  // through the loop, then stop the client  if (!client.connected() && lastConnected)  {    Serial.println();    Serial.println("disconnecting.");    client.stop();  }

  // if you're not connected, and ten seconds have passed since  // your last connection, then connect again and send data  if(!client.connected() && (millis() - lastConnectionTime > postingInterval))  {    sendData(dataString);  }  // store the state of the connection for next time through  // the loop  lastConnected = client.connected();}

Page 101: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

    // last pieces of the HTTP PUT request    client.println("Content-Type: text/csv");    client.println("Connection: close");    client.println();        // here's the actual content of the PUT request    client.println(thisData);  }   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();}

GSM Test ModemThis sketch tests the modem on the GSM shield to see if it is working correctly. You do not need a SIM card for this example.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

ShieldCircuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>Create an instance of the GSMModem class:GSMModem modem;Create a variable to hold the IMEI number of the modemString IMEI = "";

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

[Get Code]Call modem.begin() to start the modem. Send a status message depending on the outcome, and end setup().

Page 102: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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

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

[Get Code]Once reset, check the IMEI again. If it is a valid return again, the modem is functioning as expected.if(modem.getIMEI() != NULL)    {      Serial.println("Modem is functoning properly");    }

[Get Code]If, after resetting the modem, there is not a valid return from getIMEI(), report an errorelse    {      Serial.println("Error: getIMEI() failed after modem.begin()");    }

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

[Get Code]Once your code is uploaded, open the serial monitor. You should see the

HTML of http://arduino.cc print out on screen when it is received./*

 This example test if your modem is working correctly.

 Circuit: * GSM shield attached (using digital pins 2, 3, and 7)

 Created 12 Jun 2012 by David del Peral modified 21 Nov 2012 by Tom Igoe */

// libraries#include <GSM.h>

// modem verification objectGSMModem modem;

// IMEI variableString IMEI = "";

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

  // start modem test (reset and check response)  Serial.print("Starting modem test...");  if(modem.begin())     Serial.println("modem.begin() succeeded");  else    Serial.println("ERROR, no modem answer.");}

void loop(){  // get modem IMEI  Serial.print("Checking IMEI...");  IMEI = modem.getIMEI();

  // check IMEI response  if(IMEI != NULL)  {    // show IMEI in serial monitor    Serial.println("Modem's IMEI: " + IMEI);    // reset modem to check booting:    Serial.print("Reseting modem...");    modem.begin();    // get and check IMEI one more time    if(modem.getIMEI() != NULL)    {      Serial.println("Modem is functoning properly");    }    else    {

Page 103: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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

Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card with data connection

Circuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""Initialize instances of the classes you're going to use. You're going to need the GSM, GPRS, and GSMClient classes.GSMClient client;GPRS gprsAccess;GSM gsmAccess;

[Get Code]Create some status messages to send to the serial monitor:String oktext = "OK";String errortext = "ERROR";

[Get Code]

Page 104: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Create some variables to hold the server, path, and proxy you wish to connect to.char url[] = "arduino.cc";char path[] = "/";char urlproxy[] = "http://arduino.cc";

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

boolean use_proxy = false;[Get Code]

In setup, open a serial connection to the computer.void setup(){  Serial.begin(9600); }

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

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

[Get Code]In loop(), set the proxy flag to false

void loop(){  use_proxy = false;

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

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

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

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

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

Page 105: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    Serial.println(oktext);[Get Code]

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

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

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

    if(use_proxy)      res_connect = client.connect(proxy, pport);    else      res_connect = client.connect(url, 80);

[Get Code]if you have connected, make a HTTP GET request using client.print().if (res_connect)    {      client.print("GET ");

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

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

[Get Code]If no connection was made, print out an errorelse    {      // if you didn't get a connection to the server      Serial.println(errortext);    }

[Get Code]Check to see if the server returned any bytes using client.available(). If there are, read them into the responseString, then cast them into a char array. Check the array for the substring "200 OK", which indicates a valid response from arduino.cc.Serial.print("Receiving response...");

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

        char responsechar[response.length()+1];        response.toCharArray(responsechar, response.length()+1);

        if(strstr(responsechar, "200 OK") != NULL){          Serial.println(oktext);          Serial.println("TEST COMPLETE!");          test = false;        }      }

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

[Get Code]Once your code is uploaded, open the serial monitor to see the status of the connection./*

 This test asks your APN data and try to connect

Page 106: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  to arduino.cc site by GPRS.

 Circuit: * GSM shield attached

 Created 18 Jun 2012 by David del Peral */

// libraries#include <GSM.h>

// PIN Number#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess;        // GSM access: include a 'true' parameter for debug enabledGPRS gprsAccess;  // GPRS accessGSMClient client;  // Client service for TCP connection

// messages for serial monitor responseString oktext = "OK";String errortext = "ERROR";

// URL and path (for example: arduino.cc)char url[] = "arduino.cc";char urlproxy[] = "http://arduino.cc";char path[] = "/";

// variable for save response obtainedString response = "";

// use a proxyboolean use_proxy = false;

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

void loop(){  use_proxy = false;

  // start GSM shield  // if your SIM has PIN, pass it as a parameter of begin() in quotes  Serial.print("Connecting GSM network...");  if(gsmAccess.begin(PINNUMBER)!=GSM_READY)  {    Serial.println(errortext);    while(true);  }  Serial.println(oktext);

  // read APN introduced by user  char apn[50];  Serial.print("Enter your APN: ");

  readSerial(apn);  Serial.println(apn);

  // Read APN login introduced by user  char login[50];  Serial.print("Now, enter your login: ");  readSerial(login);  Serial.println(login);

  // read APN password introduced by user  char password[20];  Serial.print("Finally, enter your password: ");  readSerial(password);

  // attach GPRS  Serial.println("Attaching to GPRS with your APN...");  if(gprsAccess.attachGPRS(apn, login, password)!=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

Page 107: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

sends the request)      client.print("GET ");

      // if use a proxy, the path is arduino.cc URL      if(use_proxy)        client.print(urlproxy);      else        client.print(path);

      client.println(" HTTP/1.0");      client.println();      Serial.println(oktext);    }     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, response.length()+1);

        // if response includes a "200 OK" substring        if(strstr(responsechar, "200 OK") != NULL){          Serial.println(oktext);          Serial.println("TEST COMPLETE!");          test = false;        }      }

      // if the server's disconnected, stop the client:      if (!client.connected())      {        Serial.println();        Serial.println("disconnecting.");        client.stop();        test = false;      }    }  }}

/*  Read input serial */int readSerial(char result[])

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

GSM Scan NetworksThis example prints out the IMEI number of the modem, then checks to see if it's connected to a carrier and prints out its signal strength. It also scans for all nearby networks.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card

Circuit

Page 108: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :#define PINNUMBER ""Initialize instances of the classes you're going to use. You're going to need the GSM, GSMScanner, and GSMModemclasses.GSM gsmAccess;GSMScanner scannerNetworks;GSMModem modemTest;

[Get Code]Create a variable to hold the IMEI number, and a status messages to send to the serial monitor:

String IMEI = "";

String errortext = "ERROR";[Get Code]

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

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

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

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

[Get Code]

Page 109: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

In loop(), scan and print out all available networks. This may take some timeSerial.println("Scanning available networks. May take some seconds.");  Serial.println(scannerNetworks.readNetworks());

[Get Code]Print out the current connected carrier, and the strength of the signal. Signal strength is on a scale of 0-31, where 0 is the lowest, and 31 is the highest. close the loop().Serial.print("Current carrier: ");  Serial.println(scannerNetworks.getCurrentCarrier());

  Serial.print("Signal Strength: ");  Serial.print(scannerNetworks.getSignalStrength());  Serial.println(" [0-31]");

[Get Code]Once your code is uploaded, open the serial monitor to see the status of the connection./*

 GSM Scan Networks

 This example prints out the IMEI number of the SIM card,  then check to see if it's connected to a carrier. If so,   it prints the phone number associated with the card. Then it scans for nearby networks and prints out their signal strengths.

 Circuit: * GSM shield attached

 Created 8 Mar 2012 by Tom Igoe, implemented by Javier Carazo Modified 18 Jan 2013 by Scott Fitzgerald */

// libraries#include <GSM.h>

// PIN Number#define PINNUMBER ""

// initialize the library instanceGSM gsmAccess;     // include a 'true' parameter to enable debuggingGSMScanner scannerNetworks;GSMModem modemTest;

// Save data variables

String IMEI = "";

// serial monitor result messagesString errortext = "ERROR";

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_READY)      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.getCurrentCarrier());

  // 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.getSignalStrength());  Serial.println(" [0-31]");}

void loop(){  // scan for existing networks, displays a list of networks  Serial.println("Scanning available networks. May take some seconds.");

Page 110: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  Serial.println(scannerNetworks.readNetworks());

    // currently connected carrier  Serial.print("Current carrier: ");  Serial.println(scannerNetworks.getCurrentCarrier());

  // 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.getSignalStrength());  Serial.println(" [0-31]");

}

GSM PIN ManagementThis example helps you change or remove the PIN of a SIM card with an Arduino and GSM shield.Hardware Required

Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card

Circuit

image of the Arduino GSM Shield on top of an Arduino UnoFirst, import the GSM library#include <GSM.h>Initialize an instance of the GSMPin class.GSMPIN PINManager;Create your variables, starting with a String to hold input from the serial monitor. Also make a flag for checking f the SIM has been authenticated with a valid PIN, and messages for the serial monitor.String user_input = "";

boolean auth = false;

String oktext = "OK";String errortext = "ERROR";

[Get Code]In setup, open a serial connection to the computer. After opening the

Page 111: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

connection, send a message to the Serial Monitor indicating the sketch has started. Call PINManager.begin() to reset the modem.void setup(){  Serial.begin(9600);   Serial.println("Change PIN example\n");  PINManager.begin();

[Get Code]Check to see if the SIM is locked with a PINwhile(!auth){    int pin_query = PINManager.isPIN();    if(pin_query == 1)    {

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

[Get Code]If the PIN is valid, set the auth flag to true. Send a status message to the serial monitor indicating the result. If you enter the wrong PIN, you can try again. After 3 missed attempts, the PIN will be locked, and you'll need the PUK number to unlock.if(PINManager.checkPIN(user_input) == 0)      {        auth = true;        PINManager.setPINUsed(true);        Serial.println(oktext);      }      else      {          Serial.println("Incorrect PIN. Remember that you have 3 opportunities.");      }    }

[Get Code]If the SIM is in PUK lock mode, ask for the PUK code and a new PINelse if(pin_query == -1)    {      Serial.println("PIN locked. Enter PUK code: ");      String puk = readSerial();      Serial.print("Now, enter a new PIN code: ");      user_input = readSerial();    if(PINManager.checkPUK(puk, user_input) == 0)      {        auth = true;        PINManager.setPINUsed(true);

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

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

[Get Code]If there's no PIN number, set the auth flag to trueelse    {      // SIM does not requires authetication       Serial.println("No pin necessary.");      auth = true;    }  }

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

[Get Code]You're going to create a custom function to handle serial input from the serial monitor. Make a named function of typeString.String readSerial(){

[Get Code]While there is serial information available, read it into a new String. If a newline character is encountered, return to the main program.String text = "";  while(1)

Page 112: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

[Get Code]loop() acts as a PIN management tool, allowing you to turn the PIN on or off, and change it.void loop(){

  Serial.println("Choose an option:\n1 - On/Off PIN.");  if(PINManager.getPINUsed())    Serial.println("2 - Change PIN.");  String user_op = readSerial();  if(user_op == "1")  {    Serial.println("Enter your PIN code:");    user_input = readSerial();

    PINManager.switchPIN(user_input);  }  else if(user_op == "2" & PINManager.getPINUsed())  {    Serial.println("Enter your actual PIN code:");    String oldPIN = readSerial();    Serial.println("Now, enter your new PIN code:");    String newPIN = readSerial();

    PINManager.changePIN(oldPIN, newPIN);  }  else  {    Serial.println("Incorrect option. Try again!.");  }  delay(1000);}

[Get Code]Once your code is uploaded, open the serial monitor to work with the PIN./*

 This example helps you change your pin or remove it.

 Circuit: * GSM shield attached

 Created 12 Jun 2012 by David del Peral */

// libraries#include <GSM.h>

// pin manager objectGSMPIN PINManager;

// save input in serial by userString user_input = "";

// authenticated with PIN codeboolean auth = false;

// serial monitor result messagesString oktext = "OK";String errortext = "ERROR";

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

  Serial.println("Change PIN example\n");  PINManager.begin();

  // check if the SIM have pin lock  while(!auth){    int pin_query = PINManager.isPIN();    if(pin_query == 1)    {      // if SIM is locked, enter PIN code      Serial.print("Enter PIN code: ");      user_input = readSerial();      // check PIN code      if(PINManager.checkPIN(user_input) == 0)      {        auth = true;        PINManager.setPINUsed(true);        Serial.println(oktext);      }      else      {          // if PIN code was incorrected        Serial.println("Incorrect PIN. Remember that you have 3 opportunities.");      }    }    else if(pin_query == -1)    {      // PIN code is locked, user must enter PUK code      Serial.println("PIN locked. Enter PUK code: ");      String puk = readSerial();      Serial.print("Now, enter a new PIN code: ");      user_input = readSerial();      // check PUK code    if(PINManager.checkPUK(puk, user_input) == 0)

Page 113: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

      {        auth = true;        PINManager.setPINUsed(true);        Serial.println(oktext);      }      else      {        // if PUK o the new PIN are incorrect        Serial.println("Incorrect PUK or invalid new PIN. Try again!.");      }    }    else if(pin_query == -2)    {      // the worst case, PIN and PUK are locked      Serial.println("PIN & PUK locked. Use PIN2/PUK2 in a mobile phone.");      while(true);    }    else    {      // SIM does not requires authetication       Serial.println("No pin necessary.");      auth = true;    }  }

  // start GSM shield  Serial.print("Checking register in GSM network...");  if(PINManager.checkReg() == 0)    Serial.println(oktext);  // if you are connect by roaming  else if(PINManager.checkReg() == 1)    Serial.println("ROAMING " + oktext);    else  {    // error connection    Serial.println(errortext);    while(true);  }}

void loop(){  // Function loop implements pin management user menu  // Only if you SIM use pin lock, you can change PIN code  // user_op variables save user option

  Serial.println("Choose an option:\n1 - On/Off PIN.");  if(PINManager.getPINUsed())    Serial.println("2 - Change PIN.");  String user_op = readSerial();  if(user_op == "1")  {    Serial.println("Enter your PIN code:");    user_input = readSerial();    // activate/deactivate PIN lock    PINManager.switchPIN(user_input);

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

/*  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 ManagementThis example shows how to use the GSM Shield and Library to manage the GSM band the modem connects to.Check http://www.worldtimezone.com/gsm.html for general GSM band information. Typical regional configurations are :

Europe, Africa, Middle East: E-GSM(900)+DCS(1800)

USA, Canada, South America: GSM(850)+PCS(1900)

Mexico: PCS(1900) Brazil: GSM(850)+E-

GSM(900)+DCS(1800)+PCS(1900)Hardware Required

Arduino board

Page 114: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Arduino + Telefonica GSM/GPRS Shield

SIM cardCircuit

image of the Arduino GSM Shield on top of an Arduino Uno/* Band Management

 This sketch, for the Arduino GSM shield, checks the band currently configured in the modem and allows you to change   it.

 Please check http://www.worldtimezone.com/gsm.html Usual configurations: Europe, Africa, Middle East: E-GSM(900)+DCS(1800) USA, Canada, South America: GSM(850)+PCS(1900) Mexico: PCS(1900) Brazil: GSM(850)+E-

GSM(900)+DCS(1800)+PCS(1900)

 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 instanceGSMBand 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 you’re 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(newBandName);   // Tell the user if the operation was OK   if(operationSuccess)  {     Serial.println("Success");  }   else  {     Serial.println("Error while changing band");   } 

  if(operationSuccess)

Page 115: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  {     while(true);   } }

// This function offers the user different options// through the Serial interface// The user selects oneString askUser(){  String newBand;   Serial.println("Select band:");   // Print the different options   Serial.println("1 : E-GSM(900)");   Serial.println("2 : DCS(1800)");   Serial.println("3 : PCS(1900)");   Serial.println("4 : E-GSM(900)+DCS(1800) ex: Europe");   Serial.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am.");   Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)"); 

  // Empty the incoming buffer   while(Serial.available())   Serial.read(); 

  // Wait for an answer, just look at the first character   while(!Serial.available());   char c= Serial.read();   if(c=='1')    newBand=GSM_MODE_EGSM;   else if(c=='2')    newBand=GSM_MODE_DCS;   else if(c=='3')    newBand=GSM_MODE_PCS;   else if(c=='4')    newBand=GSM_MODE_EGSM_DCS;   else if(c=='5')    newBand=GSM_MODE_GSM850_PCS;   else if(c=='6')    newBand=GSM_MODE_GSM850_EGSM_DCS_PCS;   else    newBand=GSM_MODE_UNDEFINED;  return newBand;}

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

Hardware Required Arduino board Arduino + Telefonica GSM/GPRS

Shield SIM card with a data plan

Circuit

image of the Arduino GSM Shield on top of an Arduino UnoCode/*  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  by David Cuartielles modified 21 Nov 2012

Page 116: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

 by Tom Igoe

 http://arduino.cc/en/Tutorial/GSMToolsTestWebServer

 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 instanceGPRS gprs;GSM gsmAccess;     // include a 'true' parameter for debug enabledGSMServer server(80); // port 80 (http default)

// timeoutconst unsigned long __TIMEOUT__ = 10*1000;

void setup(){  // initialize serial communications  Serial.begin(9600);Serial.println("starting,..");  // connection state  boolean connected = true;

  // Start GSM shield  // If your SIM has PIN, pass it as a parameter of begin() in quotes  while(!connected)  {  if((gsmAccess.begin(PINNUMBER)==GSM_READY) &      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))      connected = true;    else    {

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

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

  // start server  server.begin();

  //Get IP.  IPAddress LocalIP = gprs.getIPAddress();  Serial.println("Server IP address=");  Serial.println(LocalIP);}

void loop(){  GSMClient client = server.available();

 if (client) {   if (client.available()) {    Serial.write(client.read());    }}

}

LiquidCrystal LibraryThis library allows an Arduino board to control LiquidCrystal displays (LCDs) based on the Hitachi HD44780 (or a compatible) chipset, which is found on most text-based LCDs. The library works with in either 4- or 8-bit mode (i.e. using 4 or 8 data lines in addition to the rs, enable, and, optionally, the rw control lines).Function

LiquidCrystal() begin() clear() home() setCursor() write() print() cursor() noCursor() blink() noBlink()

Page 117: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

LiquidCrystal()DescriptionCreates 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.SyntaxLiquidCrystal(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)Parametersrs: the number of the Arduino pin that is connected to the RS pin on the LCDrw: 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 LCDd0, 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()DescriptionInitializes 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.Syntaxlcd.begin(cols, rows)Parameterslcd: a variable of type LiquidCrystalcols: the number of columns that the display hasrows: the number of rows that the display has 

clear()DescriptionClears the LCD screen and positions the cursor in the upper-left corner.Syntaxlcd.clear()Parameterslcd: a variable of type LiquidCrystal

home()DescriptionPositions 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.Syntaxlcd.home()Parameterslcd: a variable of type LiquidCrystal

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

Page 118: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Syntaxlcd.setCursor(col, row)Parameterslcd: a variable of type LiquidCrystalcol: 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()DescriptionWrite a character to the LCD.Syntaxlcd.write(data)Parameterslcd: a variable of type LiquidCrystaldata: the character to write to the displayReturnsbytewrite() will return the number of bytes written, though reading that number is optionalExample#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()DescriptionPrints text to the LCD.Syntaxlcd.print(data) lcd.print(data, BASE)Parameterslcd: a variable of type LiquidCrystaldata: 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).Returnsbyteprint() will return the number of bytes written, though reading that number is optionalExample#include <LiquidCrystal.h>

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

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

void loop() {}

cursor()DescriptionDisplay the LCD cursor: an underscore (line) at the position to which the next character will be written.Syntaxlcd.cursor()Parameterslcd: a variable of type LiquidCrystalExample

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

Page 119: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Before wiring the LCD screen to your Arduino we suggest to solder a pin header strip to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image above.To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

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

Page 120: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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 pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

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

  delay(500);}

noCursor()DescriptionHides the LCD cursor.Syntaxlcd.noCursor()Parameterslcd: a variable of type LiquidCrystal

blink()DescriptionDisplay the blinking LCD cursor. If used in combination with the cursor() function, the result will depend on the particular display.Syntaxlcd.blink()Parameterslcd: a variable of type LiquidCrystalnoBlink()DescriptionTurns off the blinking LCD cursor.Syntaxlcd.noBlink()Parameterslcd: a variable of type LiquidCrystal

LiquidCrystal - blink() and noBlink()The Liquid Crystal Library allows you to control LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface.This example sketch shows how to use the blink() and noBlink() methods to blink a block-style cursor.Hardware Required

Arduino Board LCD Screen (compatible with

Hitachi HD44780 driver) pin headers to solder to the LCD

display pins 10k Potentiometer breadboard hook-up wire

Circuit

Page 121: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Before wiring the LCD screen to your Arduino we suggest to solder a pin header strip to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image above.To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

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

Page 122: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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 pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

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

display()DescriptionTurns on the LCD display, after it's been turned off with noDisplay(). This will restore the text (and cursor) that was on the display.Syntaxlcd.display()Parameterslcd: a variable of type LiquidCrystal

noDisplay()DescriptionTurns off the LCD display, without losing the text currently shown on it.Syntaxlcd.noDisplay()Parameterslcd: a variable of type LiquidCrystal

LiquidCrystal - display() and noDisplay()The Liquid Crystal Library allows you to control LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface.This example sketch shows how to use the display() and noDisplay() methods to turn on and off the display. The text to be displayed will still be preserved when you use noDisplay() so it's a quick way to blank the display without losing everything on it.Hardware Required

Arduino Board LCD Screen (compatible with

Hitachi HD44780 driver) pin headers to solder to the LCD

display pins 10k Potentiometer breadboard hook-up wire

CircuitBefore 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

Page 123: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

can see in the image above.To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

Code/*  LiquidCrystal Library - display() and noDisplay()  Demonstrates the use a 16x2 LCD display.

Page 124: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

 This example code is in the public domain.

 http://arduino.cc/en/Tutorial/LiquidCrystalDisplay

 */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

void loop() {  // Turn off the display:  lcd.noDisplay();  delay(500);   // Turn on the display:  lcd.display();

  delay(500);}

scrollDisplayLeft()DescriptionScrolls the contents of the display (text and cursor) one space to the left.Syntaxlcd.scrollDisplayLeft()Parameterslcd: a variable of type LiquidCrystal

scrollDisplayRight()DescriptionScrolls the contents of the display (text and cursor) one space to the right.Syntaxlcd.scrollDisplayRight()Parameterslcd: a variable of type LiquidCrystal

LiquidCrystal - scrollDisplayLeft() and scrollDisplayRight()The Liquid Crystal Library allows you to control LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface.This example sketch shows how to use the scrollDisplayLeft() and scrollDisplayRight() methods to reverse the direction the text is flowing. It prints "Hello World!", scrolls it offscreen to the left, then offscreen to the right, then back to home.Hardware Required

Arduino Board LCD Screen (compatible with

Hitachi HD44780 driver) pin headers to solder to the LCD

display pins 10k Potentiometer breadboard hook-up wire

CircuitBefore wiring the LCD screen to your Arduino we suggest to solder a pin header strip to the 14 (or 16) pin count

Page 125: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

connector of the LCD screen, as you can see in the image above.To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

Code/*  LiquidCrystal Library - scrollDisplayLeft() and scrollDisplayRight()  Demonstrates the use a 16x2 LCD display.

Page 126: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

 */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

void loop() {  // scroll 13 positions (string length) to the left   // to move it offscreen left:  for (int positionCounter = 0; positionCounter < 13; positionCounter++) {    // scroll one position left:

    lcd.scrollDisplayLeft();     // wait a bit:    delay(150);  }

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

}

autoscroll()DescriptionTurns 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.Syntaxlcd.autoscroll()Parameterslcd: a variable of type LiquidCrystal

noAutoscroll()DescriptionTurns off automatic scrolling of the LCD.Syntaxlcd.noAutoscroll()

Page 127: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Parameterslcd: a variable of type LiquidCrystal

leftToRight()DescriptionSet 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 previously-output text.Syntaxlcd.leftToRight()Parameterslcd: a variable of type LiquidCrystal

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

createChar()DescriptionCreate 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.Syntaxlcd.createChar(num, data)Parameterslcd: a variable of type LiquidCrystal

num: which character to create (0 to 7)data: the character's pixel dataExample#include <LiquidCrystal.h>

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

byte smiley[8] = { B00000, B10001, B00000, B00000, B10001, B01110, B00000,};

void setup() { lcd.createChar(0, smiley); lcd.begin(16, 2); lcd.write(byte(0));}

void loop() {}

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

output of the sketch on a 2x16 LCDThe LCDs have a parallel interface, meaning that the microcontroller has to

Page 128: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

Arduino Board LCD Screen (compatible with

Hitachi HD44780 driver) pin headers to solder to the LCD

display pins 10k Potentiometer

breadboard hook-up wire

CircuitBefore 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

Page 129: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

Code/*  LiquidCrystal Library - Hello World

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

 http://www.arduino.cc/en/Tutorial/LiquidCrystal */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

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

Page 130: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

LiquidCrystal - Text Direction (leftToRight() and rightToLeft()The Liquid Crystal Library allows you to control LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface.This example sketch shows how to use the leftToRight() and rightToLeft() methods. These methods control which way text flows from the cursor.rightToLeft() causes text to flow to the left from the cursor, as if the display is right-justified.leftToRight() causes text to flow to the right from the cursor, as if the display is left-justified.This sketch prints a through l right to left, then m through r left to right, then s through z right to left again.Hardware Required

Arduino Board LCD Screen (compatible with

Hitachi HD44780 driver) pin headers to solder to the LCD

display pins 10k Potentiometer breadboard hook-up wire

CircuitBefore wiring the LCD screen to your Arduino we suggest to solder a pin header strip to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image above.To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

Page 131: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.  This sketch demonstrates how to use leftToRight() and rightToLeft()  to move the cursor.  The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3)  Library originally added 18 Apr 2008 by David A. Mellis  library modified 5 Jul 2009 by Limor Fried (http://www.ladyada.net) example added 9 Jul 2009 by Tom Igoe  modified 22 Nov 2010 by Tom Igoe  This example code is in the public domain.  http://arduino.cc/en/Tutorial/LiquidCrystalTextDirection  */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int thisChar = 'a';

void setup() {  // set up the LCD's number of columns and rows:   lcd.begin(16, 2);  // turn on the cursor:  lcd.cursor();}

void loop() {  // reverse directions at 'm':  if (thisChar == 'm') {    // go right for the next letter    lcd.rightToLeft();   }  // reverse again at 's':

Page 132: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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 addednoAutoscroll() turns scrolling offThis 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

CircuitBefore wiring the LCD screen to your Arduino we suggest to solder a pin header strip to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image above.

To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

Page 133: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.  This sketch demonstrates the use of the autoscroll() and noAutoscroll() functions to make new text scroll or not.  The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3)  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/LiquidCrystalAutoscroll

 */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {  // set up the LCD's number of columns and rows:   lcd.begin(16,2);}

void loop() {  // set the cursor to (0,0):  lcd.setCursor(0, 0);  // print from 0 to 9:  for (int thisChar = 0; thisChar < 10; thisChar++) {   lcd.print(thisChar);   delay(500);  }

Page 134: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

LiquidCrystal - Serial InputThe Liquid Crystal Library allows you to control LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface.This example sketch accepts serial input from a host computer and displays it on the LCD. To use it, upload the sketch, then open the Serial Monitor and type some characters and click Send. The text will appear on your LCD.Hardware Required

Arduino Board LCD Screen (compatible with

Hitachi HD44780 driver) pin headers to solder to the LCD

display pins 10k Potentiometer breadboard hook-up wire

CircuitBefore wiring the LCD screen to your Arduino we suggest to solder a pin header strip to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image above.To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4

LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

Page 135: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.  This sketch displays text sent over the serial port   (e.g. from the Serial Monitor) on an attached LCD.  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/LiquidCrystalSerial */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup(){    // set up the LCD's number of columns and rows:   lcd.begin(16, 2);  // initialize the serial communications:  Serial.begin(9600);}

void loop(){  // when characters arrive over the serial port...  if (Serial.available()) {    // wait a bit for the entire message to arrive    delay(100);    // clear the screen    lcd.clear();    // read all the available characters    while (Serial.available() > 0) {

Page 136: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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:lcd.setCursor(0, 0); // top leftlcd.setCursor(15, 0); // top rightlcd.setCursor(0, 1); // bottom leftlcd.setCursor(15, 1); // bottom right

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

CircuitBefore wiring the LCD screen to your Arduino we suggest to solder a pin header strip to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image above.To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

Page 137: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

 */

// include the library code:#include <LiquidCrystal.h>

// these constants won't change.  But you can change the size of// your LCD using them:const int numRows = 2;const int numCols = 16;

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {  // set up the LCD's number of columns and rows:   lcd.begin(numCols,numRows);}

void loop() {  // loop from ASCII 'a' to ASCII 'z':  for (int thisLetter = 'a'; thisLetter <= 'z'; thisLetter++) {    // loop over the columns:

Page 138: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

LiquidCrystal - scrollDisplayLeft() and scrollDisplayRight()The Liquid Crystal Library allows you to control LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface.This example sketch shows how to use the scrollDisplayLeft() and scrollDisplayRight() methods to reverse the direction the text is flowing. It prints "Hello World!", scrolls it offscreen to the left, then offscreen to the right, then back to home.Hardware Required

Arduino Board LCD Screen (compatible with

Hitachi HD44780 driver) pin headers to solder to the LCD

display pins 10k Potentiometer breadboard hook-up wire

CircuitBefore wiring the LCD screen to your Arduino we suggest to solder a pin header strip to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image above.To wire your LCD screen to your Arduino, connect the following pins:

LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5

LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2

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

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

Page 139: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Code/*  LiquidCrystal Library - scrollDisplayLeft() and scrollDisplayRight()  Demonstrates the use a 16x2 LCD display.

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

 */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

void loop() {  // scroll 13 positions (string length) to the left   // to move it offscreen left:  for (int positionCounter = 0; positionCounter < 13; positionCounter++) {    // scroll one position left:

Page 140: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    lcd.scrollDisplayLeft();     // wait a bit:    delay(150);  }

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

}

SD LibraryUsing the SD library to log dataThis example shows how to use the SD card Library to log data from three analog sensors to a SD card. Please click herefor more information on the SD library.Hardware Required

Three analog sensors Arduino board SD card board Formatted SD card

Circuit

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

Page 141: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

 ** 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");  } }Using the SD library to retrieve information over a serial portThis example shows how to read a file from a SD card using the SD library and send it over the serial port. Please click here for more information on the SD library.Hardware Required

Arduino board Ethernet Shield (or other board with an

SD slot) Formatted SD card with a file named

"datalog.txt" containing some textCircuit

Page 142: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

image developed using Fritzing. For more circuit examples, see the Fritzing project pageNone, but the Arduino has to have the Ethernet Shield and a USB cable connected to the computer.CodeThe code below is configured for use with an Ethernet shield, which has an onboard SD slot. In the setup(), callSD.begin(), naming pin 4 as the CS pin. This pin varies depending on the make of shield or board you are using.On the SD card, there is a file named "datalog.txt". In the loop(), the file is opened when calling SD.open(). To send the file serially to a computer, use Serial.print(), reading the contents of the file with SD.read()./*  SD card file dump  This example shows how to read a file from the SD card using the SD library and send it over the serial port.      The circuit: * SD card attached to SPI bus as follows: ** MOSI - pin 11 ** MISO - pin 12 ** CLK - pin 13 ** CS - pin 4  created  22 December 2010 by Limor Fried modified 9 Apr 2012 by Tom Igoe  This example code is in the public domain.      */

#include <SD.h>

// On the Ethernet Shield, CS is pin 4. Note that even if it's not// used as the CS pin, the hardware CS pin (10 on most Arduino boards,// 53 on the Mega) must be left as an output or the SD library// functions will not work.const int chipSelect = 4;

void setup(){ // Open serial communications and wait for port to open:  Serial.begin(9600);   while (!Serial) {

    ; // wait for serial port to connect. Needed for Leonardo only  }

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

  // if the file is available, write to it:  if (dataFile) {    while (dataFile.available()) {      Serial.write(dataFile.read());    }    dataFile.close();  }    // if the file isn't open, pop up an error:  else {    Serial.println("error opening datalog.txt");  } }

void loop(){}

Using the SD library to create and remove files on a SD cardThis example shows how to create and destroy a file on a SD card. Please click here for more information on the SD library.Hardware Required

Arduino board Ethernet Shield (or other board with an

SD slot) Formatted SD card

Circuit

Page 143: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

  created   Nov 2010 by David A. Mellis modified 9 Apr 2012 by Tom Igoe  This example code is in the public domain.      */#include <SD.h>

File myFile;

void setup(){ // Open serial communications and wait for port to open:  Serial.begin(9600);   while (!Serial) {    ; // wait for serial port to connect. Needed for 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:

Page 144: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

void loop(){  // nothing happens after setup finishes.}

Using the SD library to read and write to a file on a SD cardhis example shows how to read and write data to and from an SD card. Please click here for more information on the SD library.Hardware Required

Arduino board Ethernet Shield (or other board with an

SD slot) Formatted SD card

Circuit

image developed using Fritzing. For more circuit examples, see the Fritzing project pageNone, but the Arduino has to have the Ethernet Shield and a USB cable connected to the computer.Code

The code below is configured for use with an Ethernet shield, which has an onboard SD slot. In the setup(), we callSD.begin(), naming pin 4 as the CS pin. This pin varies depending on the make of shield or board you are using.In setup(), create a new file with SD.open() named "test.txt". FILE_WRITE enables read and write access to the file, starting at the end. If a file "test.txt" was already on the card, that file would be opened.Name the instance of the opened file "myFile".Once opened, use myFile.println() to write a string to the card, followed by a carriage return. Once the content is written, close the file.Again, open the file with SD.open(). Once opened, ask the Arduino to read the contents of the file with SD.read() and send them over the serial port. After all the contents of the file are read, close the file with SD.close()./*  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  This example code is in the public domain.      */ #include <SD.h>

File myFile;

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

Page 145: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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");  }    // re-open the file for reading:  myFile = SD.open("test.txt");  if (myFile) {    Serial.println("test.txt:");        // read from the file until there's nothing else in it:    while (myFile.available()) {        Serial.write(myFile.read());    }    // close the file:    myFile.close();  } else {    // if the file didn't open, print an error:    Serial.println("error opening test.txt");  }}

void loop(){    // nothing happens after setup}

Using the SD library to retrieve information over a serial portThis example shows how to read information about a SD card. The example reports volume type, free space and other information using the SD library, sending it over the serial port. Please click here for more information on the SD library.Hardware Required

Arduino board Ethernet Shield (or other board with an

SD slot) Formatted SD card

Circuit

image developed using Fritzing. For more circuit examples, see the Fritzing project pageNone, but the Arduino has to have the Ethernet Shield and a USB cable connected to the computer.CodeThe code below is configured for use with an Ethernet shield, which has an onboard SD slot. In the setup(), callSD.begin(), naming pin 4 as the CS pin. This pin varies depending on the make of shield or board you are using.The code uses some undocumented utility libraries to report information about the SD card. This information includes formatting (FAT16 or FAT32) and file structure, as well as the

Page 146: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

amount of free space and space used on the card./*  SD card test     This example shows how use the utility libraries on which the' SD library is based in order to get info about your SD card. Very useful for testing a card when you're not sure whether its working or not.      The circuit:  * SD card attached to SPI bus as follows: ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila ** CS - depends on your SD card shield or module.         Pin 4 used here for consistency with other Arduino examples

  created  28 Mar 2011 by Limor Fried  modified 9 Apr 2012 by Tom Igoe */ // include the SD library:#include <SD.h>

// set up variables using the SD utility library functions:Sd2Card card;SdVolume volume;SdFile root;

// change this to match your SD shield or module;// Arduino Ethernet shield: pin 4// Adafruit SD shields and modules: pin 10// Sparkfun SD shield: pin 8const int chipSelect = 4;    

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

  Serial.print("\nInitializing SD card...");  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.

  // Note that even if it's not used as the CS pin, the hardware SS pin   // (10 on most Arduino boards, 53 on the Mega) must be left as an output   // or the SD library functions will not work.   pinMode(10, OUTPUT);     // change this to 53 on a mega

  // we'll use the initialization code from the utility libraries  // since we're just testing if the card is working!  if (!card.init(SPI_HALF_SPEED, chipSelect)) {    Serial.println("initialization failed. Things to check:");    Serial.println("* is a card is inserted?");    Serial.println("* Is your wiring correct?");    Serial.println("* did you change the chipSelect pin to match your shield or module?");    return;  } else {   Serial.println("Wiring is correct and a card is present.");   }

  // print the type of card  Serial.print("\nCard type: ");  switch(card.type()) {    case SD_CARD_TYPE_SD1:      Serial.println("SD1");      break;    case SD_CARD_TYPE_SD2:      Serial.println("SD2");      break;    case SD_CARD_TYPE_SDHC:      Serial.println("SDHC");      break;    default:      Serial.println("Unknown");  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32  if (!volume.init(card)) {    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");    return;  }

  // print the type and size of the first FAT-type volume  uint32_t volumesize;  Serial.print("\nVolume type is FAT");  Serial.println(volume.fatType(), DEC);  Serial.println();    volumesize = volume.blocksPerCluster();    // clusters are collections of blocks  volumesize *= volume.clusterCount();       // we'll have a lot of clusters

Page 147: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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 libraryThis 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.CircuitServo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the Arduino board. The signal pin is typically yellow, orange or white and should be connected to a digital pin on the Arduino board. Note that servos draw considerable power, so if you need to

drive more than one or two, you'll probably need to power them from a separate supply (i.e. not the +5V pin on your Arduino). Be sure to connect the grounds of the Arduino and external power supply together.

Functions attach() write() writeMicroseconds() read() attached() detach()

attach()DescriptionAttach 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.Syntaxservo.attach(pin) servo.attach(pin, min, max)Parametersservo: a variable of type Servopin: the number of the pin that the servo is attached tomin (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()DescriptionWrites 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

Page 148: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).Syntaxservo.write(angle)Parametersservo: a variable of type Servoangle: the value to write to the servo, from 0 to 180Example#include <Servo.h>

Servo myservo;

void setup() { myservo.attach(9); myservo.write(90); // set servo to mid-point}

void loop() {}

writeMicroseconds()DescriptionWrites 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.Syntaxservo.writeMicroseconds(uS)Parametersservo: 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()DescriptionRead the current angle of the servo (the value passed to the last call to write()).Syntaxservo.read()Parametersservo: a variable of type ServoReturnsThe angle of the servo, from 0 to 180 degrees.

attached()DescriptionCheck whether the Servo variable is attached to a pin.Syntaxservo.attached()Parametersservo: a variable of type ServoReturnstrue if the servo is attached to pin; false otherwise.

detach()DescriptionDetach 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().Syntaxservo.detach()Parametersservo: a variable of type Servo

Knob

Page 149: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Control the position of a RC (hobby) servo motor with your Arduino and a potentiometer.This example makes use of the Arduino servo library.Hardware Required

Arduino Board (1) Servo Motor (1) Potentiometer hook-up wire

CircuitServo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the Arduino board. The signal pin is typically yellow or orange and should be connected to pin 9 on the Arduino board.The potentiometer should be wired so that its two outer pins are connected to power (+5V) and ground, and its middle pin is connected to analog input 0 on the Arduino.click the images to enlarge

images developed using Fritzing. For more circuit examples, see the Fritzing project pageSchematic

Code// Controlling a servo position using a potentiometer (variable resistor) // by Michal Rinott <http://people.interaction-ivrea.it/m.rinott> 

#include <Servo.h>  Servo myservo;  // create servo object to control a servo  int potpin = 0;  // analog pin used to connect the potentiometerint 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

Page 150: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

value of the potentiometer (value between 0 and 1023)   val = map(val, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180)   myservo.write(val);                  // sets the servo position according to the scaled value   delay(15);                           // waits for the servo to get there }

SweepSweeps 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

CircuitServo 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

images developed using Fritzing. For more circuit examples, see the Fritzing project pageSchematic

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;    // variable to store the servo position  void setup() {   myservo.attach(9);  // attaches the servo on pin 9 to the servo object }   

Page 151: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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 libraryThis library allows you to communicate with SPI devices, with the Arduino as the master device.A Brief Introduction to the Serial Peripheral Interface (SPI)Serial Peripheral Interface (SPI) is a synchronous serial data protocol used by microcontrollers for communicating with one or more peripheral devices quickly over short distances. It can also be used for communication between two microcontrollers.With an SPI connection there is always one master device (usually a microcontroller) which controls the peripheral devices. Typically there are three lines common to all the devices:MISO (Master In Slave Out) - The Slave line for sending data to the master,MOSI (Master Out Slave In) - The Master line for sending data to the peripherals,SCK (Serial Clock) - The clock pulses which synchronize data transmission generated by the masterand one line specific for every device:SS (Slave Select) - the pin on each device that the master can use to enable and disable specific devices.When a device's Slave Select pin is low, it communicates with the master. When it's high, it ignores the master. This allows you to have multiple SPI devices sharing the same MISO, MOSI, and CLK lines.To write code for a new SPI device you need to note a few things:Is data shifted in Most Significant Bit (MSB) or Least Significant Bit (LSB) first? This is

controlled by the SPI.setBitOrder() function.Is the data clock idle when high or low? Are samples on the rising or falling edge of clock pulses? These modes are controlled by theSPI.setDataMode() function.What speed is the SPI running at? This is controlled by theSPI.setClockDivider() function.The SPI standard is loose and each device implements it a little differently. This means you have to pay special attention to the device's datasheet when writing your code.Generally speaking, there are four modes of transmission. These modes control whether data is shifted in and out on the rising or falling edge of the data clock signal (called the clock phase), and whether the clock is idle when high or low (called the clock polarity). The four modes combine polarity and phase according to this table:

ModeClock

Polarity (CPOL)

Clock Phase

(CPHA)SPI_MODE0 0 0SPI_MODE1 0 1SPI_MODE2 1 0SPI_MODE3 1 1The SPI.setDataMode() function lets you set the mode to control clock polarity and phase.Every SPI device has a maximum allowed speed for SPI Bus. The SPI.setClockDivider() allows you to change the clock speed to make your device working properly (default is 4MHz).Once you have your SPI parameters set correctly you just need to figure which registers in your device control which functions, and you're good to go. This will be explained in the data sheet for your device.For more on SPI, see Wikipedia's page on SPI.ConnectionsThe following table display on which pins the SPI lines are broken out on the different Arduino boards:

Arduino Board

MOSI

MISO

SCK

SS (sla

SS (master

Page 152: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

ve)

)

Uno or Duemilanove

11 or ICSP-4

12 or ICSP-1

13 or ICSP-3

10 -

Mega1280 or Mega2560

51 or ICSP-4

50 or ICSP-1

52 or ICSP-3

53 -

Leonardo

ICSP-4

ICSP-1

ICSP-3

- -

Due

ICSP-4

ICSP-1

ICSP-3

-

4, 10, 52

Note that MISO, MOSI, and SCK are available in a consistent physical location on the ICSP header; this is useful, for example, in designing a shield that works on every board.

Note about Slave Select (SS) pin on AVR based boardsAll AVR based boards have an SS pin that is useful when they act as a slavecontrolled by an external master. Since this library supports only master mode, this pin should be set always as OUTPUT otherwise the SPI interface could be put automatically into slave mode by hardware, rendering the library inoperative.It is, however, possible to use any pin as

the Slave Select (SS) for the devices. For example, the Arduino Ethernet shield uses pin 4 to control the SPI connection to the on-board SD card, and pin 10 to control the connection to the Ethernet controller.Extended SPI functionality for the DueThe Arduino Due's SPI interface works differently than any other Arduino boards. The library can be used on the Due with the same methods available to other Arduino boards or using the extended methods. The extended methods exploits the the SAM3X hardware and allows some interesting features like:automatic handling of the device slave selection.automatic handling of different device configurations (clock speed, data mode, etc) so every device can have its own configuration automatically selected.Arduino Due has three exposed pins for the devices Slave Select (SS) lines (pins 4, 10, and 52).

begin()DescriptionInitializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high.Extended method for Arduino DueIf 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 usageSyntaxSPI.begin()

SPI.begin(slaveSelectPin)

(Arduino Due only)

ParametersslaveSelectPi slave (

Page 153: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

n: device SS pin

Arduino Due only)

ReturnsNone

end()DescriptionDisables the SPI bus (leaving pin modes unchanged).Extended method for Arduino DueIf 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 usageSyntaxSPI.end()

SPI.end(slaveSelectPin)

(Arduino Due only)

ParametersslaveSelectPin:

slave device SS pin

(Arduino Due only)

ReturnsNone

setBitOrder()DescriptionSets 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 DueIf 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 usageSyntaxSPI.setBitOrder(order)

SPI.setBitOrder(slaveSelectPin, order)

(Ardui

no Due only)

Parametersorder: either LSBFIRST or MSBFIRSTReturnsNone

setClockDivider()DescriptionSets 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 DueOn 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 DueIf you specify one of the Arduino Due's Slave Select (SS) pin in the call to setClockDivider(), the clock setting is applied only to the device connected to the specified SS pin. More info on extended methods: Due Extended SPI usageSyntaxSPI.setClockDivider(divider)

SPI.setClockDivider(slaveSelectPin, divider)

(Arduino Due only)

Parametersdivider: SPI_CLOC

K_DIV2 SPI_CLOC

K_DIV4 SPI_CLOC

K_DIV8 SPI_CLOC

K_DIV16 SPI_CLOC

K_DIV32 SPI_CLOC

K_DIV64 SPI_CLOC

K_DIV128

(On AVR boards)

Page 154: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

slaveSelectPin:

slave device SS pin

(Arduino Due only)

divider: a number from 1 to 255

(Arduino Due only)

ReturnsNone

setDataMode()DescriptionSets the SPI data mode: that is, clock polarity and phase. See the Wikipedia article on SPI for details.Extended method for Arduino DueIf 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 usageSyntaxSPI.setDataMode(mode)

SPI.setDataMode(slaveSelectPin, mode)

(Arduino Due only)

Parametersmode: SPI_MOD

E0 SPI_MOD

E1 SPI_MOD

E2 SPI_MOD

E3slaveSelectPin

slave device SS pin

(Arduino Due only)

ReturnsNone

transfer()

DescriptionTransfers one byte over the SPI bus, both sending and receiving.Extended method for Arduino DueIf 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 usageSyntaxSPI.transfer(val)

SPI.transfer(slaveSelectPin, val)

(Arduino Due only)

SPI.transfer(slaveSelectPin, val, transferMode)

(Arduino Due only)

Parametersval: the byte to

send out over the bus

slaveSelectPin:

slave device SS pin

(Arduino Due only)

transferMode:

SPI_CONTINUE: keeps the SS pin low, allowing a subsequen

(Optional, Arduino Due only)

Page 155: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

t byte transfer.

SPI_LAST: default if not specified the SS pin returns to high after one byte has been transferred.

Returnsthe byte read from the bus.

Extended SPI library usage with the DueOn 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.UseYou must specify each pin you wish to use as CS for the SPI devices.It is possible for the Due to automatically handle the chip selection between multiple devices sharing the SPI bus. Each device may have also different attribues such as speed and datamode.If using multiple devices with different CS pins, you'll need to declare those pins in setup(). In the following example, there are two devices that share the SPI MISO, MOSI, and SCK pins. One device CS is attached to pin 4, the other to pin 10.void setup(){  // initialize the bus for a device on pin 4  SPI.begin(4);  // initialize the bus for a device on pin 10  SPI.begin(10);}

[Get Code]Once a pin has been declared as a CS pin, it's possible to change its default behaviors as well. For example, if the devices run at different clock speeds, the setup() may look like this :void setup(){  // initialize the bus for the device on pin 4

  SPI.begin(4);  // Set clock divider on pin 4 to 21  SPI.setClockDivider(4, 21);   // initialize the bus for the device on pin 10  SPI.begin(10);  // Set clock divider on pin 10 to 84  SPI.setClockDivider(10, 84);}

[Get Code]A single byte transfer to a device on pin 4 could look like this :void loop(){  byte response = SPI.transfer(4, 0xFF);}

[Get Code]In the above, “0xFF” is sent to the SPI device on pin 4 and the data coming from MISO is saved inside the variableresponse. The chip selection is handled automatically by the SPI controller, the transfer command implies the following:

Select device by setting pin 4 to LOW Send 0xFF through the SPI bus and

return the byte received Deselect device by setting pin 4 to

HIGHIt's possible to send more than one byte in a transaction by telling the the transfer command to not deselect the SPI device after the transfer :void loop(){//transfer 0x0F to the device on pin 10, keep the chip selectedSPI.transfer(10, 0xF0, SPI_CONTINUE);//transfer 0x00 to the device on pin 10, keep the chip selectedSPI.transfer(10, 0×00, SPI_CONTINUE);//transfer 0x00 to the device on pin 10, store byte received in response1, keep the chip selectedbyte response1 = SPI.transfer(10, 0×00, SPI_CONTINUE);//transfer 0x00 to the device on pin 10, store byte received in response2, deselect the chipbyte response2 = SPI.transfer(10, 0×00);}

[Get Code]The parameter SPI_CONTINUE ensures that chip selection is keep active between transfers. On the last transfer SPI_CONTINUE is not specified as it's the last byte transferred.See the individual reference pages for setClockDivider(), setDataMode(), tr

Page 156: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

ansfer(), setBitOrder() for proper syntax when using the extended methods.NB : once SPI.begin() is called, the declared pin will not be available as a general purpose I/O pin

Extended SPI library usage with the DueOn 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.UseYou must specify each pin you wish to use as CS for the SPI devices.It is possible for the Due to automatically handle the chip selection between multiple devices sharing the SPI bus. Each device may have also different attribues such as speed and datamode.If using multiple devices with different CS pins, you'll need to declare those pins in setup(). In the following example, there are two devices that share the SPI MISO, MOSI, and SCK pins. One device CS is attached to pin 4, the other to pin 10.void setup(){  // initialize the bus for a device on pin 4  SPI.begin(4);  // initialize the bus for a device on pin 10  SPI.begin(10);}

[Get Code]Once a pin has been declared as a CS pin, it's possible to change its default behaviors as well. For example, if the devices run at different clock speeds, the setup() may look like this :void setup(){  // initialize the bus for the device on pin 4  SPI.begin(4);  // Set clock divider on pin 4 to 21  SPI.setClockDivider(4, 21);   // initialize the bus for the device on pin 10  SPI.begin(10);  // Set clock divider on pin 10 to 84  SPI.setClockDivider(10, 84);}

[Get Code]

A single byte transfer to a device on pin 4 could look like this :void loop(){  byte response = SPI.transfer(4, 0xFF);}

[Get Code]In the above, “0xFF” is sent to the SPI device on pin 4 and the data coming from MISO is saved inside the variableresponse. The chip selection is handled automatically by the SPI controller, the transfer command implies the following:

Select device by setting pin 4 to LOW Send 0xFF through the SPI bus and

return the byte received Deselect device by setting pin 4 to

HIGHIt's possible to send more than one byte in a transaction by telling the the transfer command to not deselect the SPI device after the transfer :void loop(){//transfer 0x0F to the device on pin 10, keep the chip selectedSPI.transfer(10, 0xF0, SPI_CONTINUE);//transfer 0x00 to the device on pin 10, keep the chip selectedSPI.transfer(10, 0×00, SPI_CONTINUE);//transfer 0x00 to the device on pin 10, store byte received in response1, keep the chip selectedbyte response1 = SPI.transfer(10, 0×00, SPI_CONTINUE);//transfer 0x00 to the device on pin 10, store byte received in response2, deselect the chipbyte response2 = SPI.transfer(10, 0×00);}

[Get Code]The parameter SPI_CONTINUE ensures that chip selection is keep active between transfers. On the last transfer SPI_CONTINUE is not specified as it's the last byte transferred.See the individual reference pages for setClockDivider(), setDataMode(), transfer(), setBitOrder() for proper syntax when using the extended methods.NB : once SPI.begin() is called, the declared pin will not be available as a general purpose I/O pin

Page 157: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Controlling a Digital Potentiometer Using SPIExamples > SPI LIbraryIn this tutorial you will learn how to control the AD5206 digital potentiometer using Serial Peripheral Interface (SPI). For an explanation of SPI see the SPI EEPROM tutorial.Digital potentiometers are useful when you need to vary the resistance in a circuit electronically rather than by hand. Example applications include LED dimming, audio signal conditioning and tone generation. In this example we will use a six channel digital potentiometer to control the brightness of six LEDs. The steps we will cover for implementing SPI communication can be modified for use with most other SPI devices.Hardware Required

AD5206 Digital Potentiometer Arduino Microcontroller Module 6 Light Emitting Diodes (LEDs) 6 220 ohm resistors Hookup Wire

Introduction to the AD5206 Digital PotentiometerClick for for the AD5206's datasheet.

The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors (potentiometers) built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1. For example, in this tutorial we will be using each variable resistor as a

Page 158: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

voltage divider by pulling one side pin (pin B) high, pulling another side pin (pin A) low and taking the variable voltage output of the center pin (Wiper). In this case, the AD5206 provides a maximum resistance of 10K ohms, delivered in 255 steps (255 being the max, 0 being the least).Circuit

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

Page 159: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

with the resistance value for the channel (0 - 255).    The circuit:  * All A pins  of AD5206 connected to +5V  * All B pins of AD5206 connected to ground  * An LED and a 220-ohm resisor in series connected from each W pin to ground  * CS - to digital pin 10  (SS pin)  * SDI - to digital pin 11 (MOSI pin)  * CLK - to digital pin 13 (SCK pin)  created 10 Aug 2010  by Tom Igoe  Thanks to Heather Dewey-Hagborg for the original tutorial, 2005 */

// inslude the SPI library:#include <SPI.h>

// set pin 10 as the slave select for the digital pot:const int slaveSelectPin = 10;

void setup() {  // set the slaveSelectPin as an output:  pinMode (slaveSelectPin, OUTPUT);  // initialize SPI:  SPI.begin(); }

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

Page 160: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  SPI.transfer(value);  // take the SS pin high to de-select the chip:  digitalWrite(slaveSelectPin,HIGH); }

SoftwareSerial LibraryThe Arduino hardware has built-in support for serial communication on pins 0 and 1 (which also goes to the computer via the USB connection). The native serial support happens via a piece of hardware (built into the chip) called a UART. This hardware allows the Atmega chip to receive serial communication even while working on other tasks, as long as there room in the 64 byte serial buffer.The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.The version of SoftwareSerial included in 1.0 and later is based on the NewSoftSerial library by Mikal Hart.LimitationsThe library has the following known limitations:

If using multiple software serial ports, only one can receive data at a time.

Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

Not all pins on the Leonardo support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).If your project requires simultaneous data flows, see Paul Stoffregen's AltSoftSerial library. AltSoftSerial overcomes a number of other issues with the core SoftwareSerial, but has it's own

limitations. Refer to the AltSoftSerial site for more information.Example/*  Software serial multple serial test  Receives from the hardware serial, sends to software serial. Receives from software serial, sends to hardware serial.  The circuit:  * RX is digital pin 10 (connect to TX of other device) * TX is digital pin 11 (connect to RX of other device)  Note: Not all pins on the Mega and Mega 2560 support change interrupts,  so only the following can be used for RX:  10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69  Not all pins on the Leonardo support change interrupts,  so only the following can be used for RX:  8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).  created back in the mists of time modified 25 May 2012 by Tom Igoe based on Mikal Hart's example  This example code is in the public domain.  */#include <SoftwareSerial.h>

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

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

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port  mySerial.begin(4800);  mySerial.println("Hello, world?");}

void loop() // run over and over{

Page 161: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  if (mySerial.available())    Serial.write(mySerial.read());  if (Serial.available())    mySerial.write(Serial.read());}

[Get Code]Functions

SoftwareSerial () available () begin () isListening () overflow () peek () read () print () println () listen () write ()

SoftwareSerial(rxPin, txPin)DescriptionA 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.ParametersrxPin: the pin on which to receive serial datatxPin: the pin on which to transmit serial dataExample#define rxPin 2#define txPin 3

// set up a new serial portSoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

SoftwareSerial: available()DescriptionGet 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.SyntaxmySerial.available()Parametersnone

Returnsthe number of bytes available to readExample// include the SoftwareSerial library so you can use its functions:#include <SoftwareSerial.h>

#define rxPin 10#define txPin 11

// set up a new serial portSoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

void setup()  {  // define pin modes for tx, rx:  pinMode(rxPin, INPUT);  pinMode(txPin, OUTPUT);  // set the data rate for the SoftwareSerial port  mySerial.begin(9600);}

void loop() {  if (mySerial.available()>0){  mySerial.read(); }}

SoftwareSerial: begin(speed)DescriptionSets 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.Parametersspeed: the baud rate (long)ReturnsnoneExample// include the SoftwareSerial library so you can use its functions:#include <SoftwareSerial.h>

#define rxPin 10#define txPin 11

// set up a new serial portSoftwareSerial 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);}

Page 162: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

void loop() {  // ...}

SoftwareSerial: isListening()DescriptionTests to see if requested software serial port is actively listening.SyntaxmySerial.isListening()ParametersnoneReturnsbooleanExample#include <SoftwareSerial.h>

// software serial : TX = digital pin 10, RX = digital pin 11SoftwareSerial 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()DescriptionTests 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.SyntaxmySerial.overflow()ParametersnoneReturnsboolean

Example#include <SoftwareSerial.h>

// software serial : TX = digital pin 10, RX = digital pin 11SoftwareSerial 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: peekDescriptionReturn 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).ParametersnoneReturnsthe character read, or -1 if none is availableExampleSoftwareSerial mySerial(10,11);

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

void loop(){  char c = mySerial.peek();}

SoftwareSerial: readDescriptionReturn a character that was received on the RX pin of the software serial

Page 163: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

port. Note that only one SoftwareSerialinstance can receive incoming data at a time (select which one with the listen() function).ParametersnoneReturnsthe character read, or -1 if none is availableExampleSoftwareSerial mySerial(10,11);

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

void loop(){  char c = mySerial.read();}

SoftwareSerial: print(data)DescriptionPrints data to the transmit pin of the software serial port. Works the same as the Serial.print() function.Parametersvary, see Serial.print() for detailsReturnsbyteprint() will return the number of bytes written, though reading that number is optionalExampleSoftwareSerial serial(10,11);int analogValue;

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

void loop(){  // read the analog input on pin 0:  analogValue = analogRead(A0);

  // print it out in many formats:  serial.print(analogValue);         // print as an ASCII-encoded decimal  serial.print("\t");                // print a tab character  serial.print(analogValue, DEC);    // print as an ASCII-encoded decimal  serial.print("\t");                // print a tab

character  serial.print(analogValue, HEX);    // print as an ASCII-encoded hexadecimal  serial.print("\t");                // print a tab character  serial.print(analogValue, OCT);    // print as an ASCII-encoded octal  serial.print("\t");                // print a tab character  serial.print(analogValue, BIN);    // print as an ASCII-encoded binary  serial.print("\t");                // print a tab character  serial.print(analogValue/4, BYTE); // print as a raw byte value (divide the                                     // value by 4 because analogRead() returns numbers                                     // from 0 to 1023, but a byte can only hold values                                     // up to 255)  serial.print("\t");                // print a tab character      serial.println();                  // print a linefeed character

  // delay 10 milliseconds before the next reading:  delay(10);}

SoftwareSerial: println(data)DescriptionPrints 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.Parametersvary, see Serial.println() for detailsReturnsbyteprintln() will return the number of bytes written, though reading that number is optionalExampleSoftwareSerial 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:

Page 164: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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()DescriptionEnables 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).SyntaxmySerial.listen()ParametersmySerial:the name of the instance to listenReturnsNoneExample#include <SoftwareSerial.h>

// software serial : TX = digital pin 10, RX =

digital pin 11SoftwareSerial portOne(10, 11);

// software serial : TX = digital pin 8, RX = digital pin 9SoftwareSerial portTwo(8, 9);

void setup(){  // Start the hardware serial port  Serial.begin(9600);

  // Start both software serial ports  portOne.begin(9600);  portTwo.begin(9600);

}

void loop(){  portOne.listen();

  if (portOne.isListening()) {   Serial.println("Port One is listening!"); }else{   Serial.println("Port One is not listening!"); }

  if (portTwo.isListening()) {   Serial.println("Port Two is listening!"); }else{   Serial.println("Port Two is not listening!"); }

}

SoftwareSerial: write(data)DescriptionPrints data to the transmit pin of the software serial port as raw bytes. Works the same as the Serial.write() function.ParametersSerial.write() for detailsReturnsbytewrite() will return the number of bytes written, though reading that number is optionalExampleSoftwareSerial mySerial(10, 11);

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

void loop()

Page 165: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

{  mySerial.write(45); // send a byte with the value 45

   int bytesSent = mySerial.write(“hello”); //send the string “hello” and return the length of the string.}

Stepper LibraryThis library allows you to control unipolar or bipolar stepper motors. To use it you will need a stepper motor, and the appropriate hardware to control it. For more on that, see Tom Igoe's notes on steppers.Circuits

Unipolar Steppers Bipolar Steppers

Functions Stepper (steps, pin1, pin2) Stepper (steps, pin1, pin2, pin3, pin4) setSpeed (rpm) step (steps)

Circuits for Unipolar Stepper Motors

Two Pins

Page 166: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Four Pins

Circuit for Bipolar Stepper MotorTwo Pins

Four Pins

Stepper(steps, pin1, pin2)Stepper(steps, pin1, pin2, pin3, pin4)DescriptionThis function creates a new instance of the Stepper class that represents a particular stepper motor attached to your Arduino board. Use it at the top of your sketch, above setup() and loop(). The number of parameters depends on how you've wired your motor - either using two or four pins of the Arduino board.Parameterssteps: the number of steps in one revolution of your motor. If your motor gives the number of degrees per step, divide that number into 360 to get the number of steps (e.g. 360 / 3.6 gives 100 steps). (int)pin1, pin2: two pins that are attached to the motor (int)pin3, pin4: optional the last two pins attached to the motor, if it's connected to four pins (int)

Page 167: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

ReturnsA new instance of the Stepper motor class.ExampleStepper myStepper = Stepper(100, 5, 6);

Stepper: setSpeed(rpms)DescriptionSets 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().Parametersrpms: the speed at which the motor should turn in rotations per minute - a positive number (long)ReturnsNone

Stepper Motor KnobStepper motors, due to their unique design, can be controlled to a high degree of accuracy without any feedback mechanisms. The shaft of a stepper, mounted with a series of magnets, is controlled by a series of electromagnetic coils that are charged positively and negatively in a specific sequence, precisely moving it forward or backward in small "steps".There are two types of steppers, Unipolars and Bipolars, and it is very important to know which type you are working with. For each of the motors, there is a different circuit. The example code will control both kinds of motors. See theunipolar and bipolar motor schematics for information on how to wire up your motor.In this example, a potentiometer (or other sensor) on analog input 0 is used to control the movement of a stepper motor using the Arduino Stepper Library. The stepper is controlled by with digital pins 8, 9, 10, and 11 for either unipolar or bipolar motors.The Arduino will connect to a U2004 Darlington Array if you're using a unipolar

stepper or a SN754410NE H-Bridge if you have a bipolar motor.For more information about the differences of the two types, please take a look at Tom Igoe's page on stepper motors.Hardware Required

Arduino Board potentiometer stepper motor U2004 Darlington Array (if using a

unipolar stepper) SN754410ne H-Bridge (if using a

bipolar stepper) power supply appropriate for your

particular stepper breadboard hookup wire

CircuitsBelow you'll find circuits for both unipolar and bipolar steppers. In either case, it is best to power your stepper motors from an external supply, as they draw too much to be powered directly from your Arduino board.In both circuits, connect a 10k pot to power and ground, with it's wiper outputting to analog pin 0.Note: Both circuits below are four wire configurations. Two wire configurations will not work with the code provided.Unipolar Stepper Circuit and schematicShow images for the unipolar circuit and schematicBipolar Stepper Circuit and schematicShow images for the bipolar circuit and schematicCodeFor 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>

Page 168: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

// change this to the number of steps on your motor#define STEPS 100

// create an instance of the stepper class, specifying// the number of steps of the motor and the pins it's// attached toStepper stepper(STEPS, 8, 9, 10, 11);

// the previous reading from the analog inputint previous = 0;

void setup(){  // set the speed of the motor to 30 RPMs  stepper.setSpeed(30);}

void loop(){  // get the sensor value  int val = analogRead(0);

  // move a number of steps equal to the change in the  // sensor reading  stepper.step(val - previous);

  // remember the previous value of the sensor  previous = val;}

TFT LCD libraryThe TFT library is included with Arduino IDE 1.0.5 and later.This library enables an Arduino board to communicate with the Arduino TFT LCD screen. It simplifies the process for drawing shapes, lines, images, and text to the screen.The Arduino TFT library extends the Adafruit GFX, and Adafruit ST7735 libraries that it is based on. The GFX library is responsible for the drawing routines, while the ST7735library is specific to the screen on the Arduino TFT. The Arduino specific additions were designed to work as similarly to the Processing API as possible.Onboard the screen is a SD card slot, which can be used through the SD library.The TFT library relies on the SPI library for communication with the screen and SD card, and needs to be included in all sketches.Using the library

The screen can be configured for use in two ways. One is to use an Arduino's hardware SPI interface. The other is to declare all the pins manually. There is no difference in the functionality of the screen between the two methods, but using hardware SPI is significantly faster.If you plan on using the SD card on the TFT module, you must use hardware SPI. All examples in the library are written for hardware SPI use.If using hardware SPI with the Uno, you only need to declare the CS, DC, and RESET pins, as MOSI (pin 11) and SCLK (pin 13) are already defined.#define CS   10#define DC   9#define RESET  8 

TFT myScreen = TFT(CS, DC, RESET);[Get Code]

To use hardware SPI with the Leonardo, you declare the pins like so :#define CS   7#define DC   0#define RESET  1

TFT myScreen = TFT(CS, DC, RESET);[Get Code]

When not using hardware SPI, you can use any available pins, but you must declare the MOSI and SCLK pins in addition to CD, DC, and RESET.#define SCLK 4#define MOSI 5#define CS   6#define DC   7#define RESET 8 

TFT myScreen = TFT(CS, DC, MOSI, SCLK, RESET);

[Get Code]Using the Arduino Esplora and the TFT libraryAs the Arduino Esplora has a socket designed for the TFT, and the pins for using the screen are fixed, an Esplora only object is created when targeting sketches for that board. You can reference the screen attached to an Esplora through EsploraTFT.Similarities to ProcessingProcessing 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

Page 169: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.ExamplesThere are two groups of examples for the TFT. There are examples specific to the Arduino Esplora, and examples that are designed for boards like the Uno or Leonardo. It should be easy to translate from one to the other once you've gotten a handle on the library and its functionality.EsploraEsplora TFT Bitmap Logo : Read an image file from a micro-SD card and draw it at random locations.Esplora TFT Color Picker : Using the joystick and slider, change the color of the TFT screenEsplora TFT Etch a Sketch : An Esplora implementation of the classic Etch-a-SketchEsplora TFT Graph : Graph the values from the light sensor to the TFTEsplora TFT Horizon : Draw an artificial horizon line based on the tilt from the accelerometerEsplora TFT Pong : A basic implementation of the classic gameEsplora TFT Temperature : Check the temperature with the onboard sensor and display it on screenArduinoTFT Bitmap Logo : Read an image file from a micro-SD card and draw it at random locations.TFT Display Text  : Read the value of a sensor and print it on the screen.TFT Pong : An Arduino implementation of the classic gameEtch a Sketch : An Arduino version of the classic Etch-a-SketchColor Picker : With three sensors, change the color of the TFT screenGraph : Graph the values from a variable resistor to the TFTFor additional information on the TFT screen, see the Getting Started page and thehardware page. 

TFTDescriptionThe 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 pinsParameters

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 SPIReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino LCD library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white  screen.stroke(255,255,255);

  // turn off fill coloring  screen.noFill();

  // draw a rectangle in the center of screen  screen.line(screen.width()/2-5, screen.height()/2-5, 10, 10);}

void loop() {

}

EsploraTFT

Page 170: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

DescriptionThis is the named instance of the TFT class when targeting the Arduino Esplora board.SyntaxEsploraTFTParametersnoneReturnsnoneExample#include <Esplora.h>#include <SPI.h>#include <TFT.h>            // Arduino LCD library

void setup() {  // initialize the screen  EsploraTFT.begin();

  // make the background white  EsploraTFT.background(255,255,255);}

void loop() {

}

beginDescriptionMust be called to initialize the Arduino GLCD screen before drawing anything.Syntaxscreen.begin()ParametersnoneReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino LCD library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background white  screen.background(255,255,255);}

void loop() {

}

backgroundDescriptionErases 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 blue channels, the screen does not display with this fidelity. The red and blue values are scaled to 5-bit color (32 discrete steps), and the green is 6-bit color (64 discrete steps).Syntaxscreen.background(red, green, blue);Parameters

red : int 0-255 green : int 0-255 blue : int 0-255

ReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino LCD library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background white  screen.background(255,255,255);}

void loop() {

}

strokeDescriptionCalled 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

Page 171: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

scaled to 5-bit color (32 discrete steps), and the green is 6-bit color (64 discrete steps).Syntaxscreen.stroke(red, green, blue);Parameters

red : int 0-255 green : int 0-255 blue : int 0-255

ReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino LCD library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white  screen.stroke(255,255,255);

  // draw a box with a white outline in the middle of the screen  screen.rect(screen.width()/2+10,screen.height()/2+10,screen.width()/2-10,screen.height()/2-10);}

void loop() {

}

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

Syntaxscreen.stroke(red, green, blue);Parameters

red : int 0-255 green : int 0-255 blue : int 0-255

ReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino LCD library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white  screen.stroke(255,255,255);

  // draw a box with a white outline in the middle of the screen  screen.rect(screen.width()/2+10,screen.height()/2+10,screen.width()/2-10,screen.height()/2-10);}

void loop() {

}

noStrokeDescriptionAfter calling this, any shapes drawn on screen will not have an outline stroke color.Syntaxscreen.noStroke();ParametersnoneReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10

Page 172: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

#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()/2-5, screen.height()/2-5, 10, 10);}

void loop() {

}

noFillDescriptionAfter calling this, any shapes drawn on screen will not be filled in.Syntaxscreen.noFill();ParametersnoneReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // turn the fill off  screen.noFill();

  // set the stroke color to white  screen.stroke(255,255,255);

  // draw a rectangle in the center of screen  screen.line(screen.width()/2-5, screen.height()/2-5, 10, 10);}

void loop() {

}

textDescriptionWrite text to the screen at the given coordinates.Syntaxscreen.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 screenReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the text color to white  screen.stroke(255,255,255);

  // write text to the screen in the top left corner  screen.text("Testing!", 0, 0);}

void loop() {

}

setTextSize

Page 173: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

DescriptionSets 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.Syntaxscreen.setTextSize(size);Parameters

size : int 1-5ReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // 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() {

}

beginDescriptionMust be called to initialize the Arduino GLCD screen before drawing anything.Syntaxscreen.begin()ParametersnoneReturnsnone

Example#include <SPI.h>#include <TFT.h>            // Arduino LCD library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background white  screen.background(255,255,255);}

void loop() {

}

pointDescriptionDraws 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.Syntaxscreen.fill(xPos, yPos);Parameters

xPos : int, the horizontal position of the point

yPos : int, the vertical position of the pointReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white  screen.fill(255,255,255);

Page 174: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  // draw a pixel in the screen's center  screen.point(screen.width()/2, screen.height()/2);}

void loop() {

}

lineDescriptionDraws a line between two points. Use stroke() to change the color of something drawn with line().Syntaxscreen.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 endsReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white  screen.stroke(255,255,255);

  // draw a diagonal line across the screen's center  screen.line(0, 0, 160, 124);}

void loop() {

}

rectDescriptionDraws 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.Syntaxscreen.rect(xStart, yStart, xEnd, yEnd);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

ReturnsnoneExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white  screen.stroke(255,255,255);

  // set the fill color to grey  screen.fill(127,127,127);

  // draw a rectangle in the center of screen  screen.line(screen.width()/2-5, screen.height()/2-5, 10, 10);}

void loop() {

}

widthDescriptionReports the width of the TFT screen in pixels.

Page 175: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Syntaxscreen.width();ParametersnoneReturnsint : the width of the screen in pixelsExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white  screen.stroke(255,255,255);

  // set the fill color to grey  screen.fill(127,127,127);

  // draw a rectangle in the center of screen  screen.line(screen.width()/2-5, screen.height()/2-5, 10, 10);}

void loop() {

}

heightDescriptionReports the height of the TFT screen in pixels.Syntaxscreen.height();ParametersnoneReturnsint : the height of the screen in pixelsExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white  screen.stroke(255,255,255);

  // set the fill color to grey  screen.fill(127,127,127);

  // draw a rectangle in the center of screen  screen.line(screen.width()/2-5, screen.height()/2-5, 10, 10);}

void loop() {

}

circleDescriptionDraws 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.Syntaxscreen.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 circleReturnsint : the width of the screen in pixelsExample#include <SPI.h>#include <TFT.h>            // Arduino TFT library

#define cs   10#define dc   9#define rst  8

TFT screen = TFT(cs, dc, rst);

void setup() {  // initialize the screen  screen.begin();

  // make the background black  screen.background(0,0,0);

  // set the stroke color to white

Page 176: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  screen.stroke(255,255,255);

  // set the fill color to grey  screen.fill(127,127,127);

  // draw a circle in the center of screen  screen.circle(screen.width()/2, screen.height()/2, 10);}

void loop() {

}

imageDescriptionDraws an image from the SD card to the screen at a specified location.Syntaxscreen.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

drawingReturnsnoneExample// this example looks for a file named "logo.bmp"//  on the SD card, and renders it to the screen#include <Esplora.h>#include <SPI.h>#include <SD.h>#include <TFT.h>            // Arduino TFT library

#define SD_CS    8  // Chip select line for SD 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() {

}

loadImageDescriptionLoads an image file from the SD card into a named instance of PImage.Syntaxscreen.loadImage(name);Parameters

name : char array, the name of the image from the SD card you wish to readReturnsnoneExample// 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    8  // Chip select line for SD 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);  }

Page 177: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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() {

}

PImageDescriptionThe base class for drawing a bitmap image from the SD card onscreen. You must include the SD library to use PImage.SyntaxPImage image;Parametersimage : the name of the PImage object. You'll refer to this when drawing images on screen.ReturnsnoneExample// 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    8  // Chip select line for SD 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() {

}

PImage.heightDescriptionChecks the height of the PImage object.Syntaximage.height();ParametersnoneReturnsint : the image's height in pixelsExample// 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    8  // Chip select line for SD 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);

Page 178: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  }

}

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.widthDescriptionChecks the width of the PImage object.Syntaximage.width();ParametersnoneReturnsint : the image's width in pixelsExample// 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    8  // Chip select line for SD 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.isValidDescriptionChecks if a named instance of PImage references a valid bitmap file.Syntaximage.isValid();ParametersnoneReturnsbooleanExample// 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    8  // Chip select line for SD 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

Page 179: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    Esplora.writeRed(255);  }

  // draw the image on the screen starting at the top left corner  EsploraTFT.image(logo, 0, 0);

}

void loop() {

}

TFT Bitmap Logo

This example for the Arduino TFT screen reads a bitmap file from a SD card and displays it on screen in a random location.For this example to work, you need to save an image named "logo.bmp" to the root of the SD card. The SD card needs to be FAT16 and FAT32 formatted. See the SD library documentation for more information on working with SD cards.Hardware Required

Arduino Uno Arduino TFT screen micro-SD card image file

CircuitInsert the SD card with the "logo.bmp" file into the SD card slot on the back of your screen.Connect power and ground to the breadboard. Show me how to do thatConnect the screen to the breadboard. The headers on the side of the screen with the small blue tab and arrow should be the ones that attach to the

board. Pay attention to the orientation of the screen, in these images, it is upside down. Show me how to do thatConnect the BL and +5V pins to power, and GND to ground. Connect CS-LD to pin 10, DC to pin 9, RESET to pin 8, MOSI to pin 11, and SCK to pin 13. If uyou're using a Leonardo, you'll be using different pins. see the getting started page for more details.Show me how to do thatCodeTo use the screen you must first include the SPI and TFT libraries. You also need to include the SD library to read the image from the card.#include <SD.h>#include <SPI.h>#include <TFT.h>

[Get Code]Define the pins you're going to use for controlling the screen, and a pin for the SD chip select. Create an instance of the TFT library named TFTscreen.#define sd_cs  4#define lcd_cs 10#define dc     9#define rst    8  

TFT TFTscreen = TFT(cs, dc, rst);[Get Code]

There is a special datatype called PImage for holding image information. Create a named version of PImagePImage logo;

[Get Code]In setup(), you're going to initialize the serial port and wait for it to become active before starting up. If you want to ignore the status information, comment out the while() loop.Once serial communication has started, initialize the SD library. If there is an error, send a message to the serial monitor.void setup() {  Serial.begin(9600);  while (!Serial) {  }

  Serial.print("Initializing SD card...");  if (!SD.begin(SD_CS)) {

Page 180: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    Serial.println("failed!");    return;  }  Serial.println("OK!");

[Get Code]Initialize and clear the screenTFTscreen.begin();  TFTscreen.background(255, 255, 255);

[Get Code]Read the image file into the PImage you named earlier with loadimage(). loadImage() prints out some useful information about the image to the serial monitor.logo = TFTscreen.loadImage("logo.bmp");  if (!logo.isValid()) {    Serial.println("error while loading arduino.bmp");  }}

[Get Code]If the image wasn't loaded correctly, stop the sketch before going any further.void loop() {  if (logo.isValid() == false) {    return;  }

[Get Code]If the image information is valid, pick a random spot on the screen to display the image. To make sure all the image is drawn onscreen, take the dimensions of the image and subtract that from the screen's dimensions.int x = random(TFTscreen.width() - logo.width());  int y = random(TFTscreen.height() - logo.height());

[Get Code]Draw the image onscreen starting at the random coordinates from the previous step, and wait for a little bit before entering the next loop()TFTscreen.image(logo, x, y);

  delay(1500);}

[Get Code]The complete sketch is below :/*

 Arduino TFT Bitmap Logo example  This example reads an image file from a micro-SD card and draws it on the screen, at random locations.

   In this sketch, the Arduino logo is read from a micro-SD card. There is a .bmp file included with this sketch.   - open the sketch folder (Ctrl-K or Cmd-K) - copy the "arduino.bmp" file to a micro-SD - put the SD into the SD slot of the Arduino TFT module.  This example code is in the public domain.  Created 19 April 2013 by Enrico Gueli  http://arduino.cc/en/Tutorial/TFTBitmapLogo  */ // include the necessary libraries#include <SPI.h>#include <SD.h>#include <TFT.h>  // Arduino LCD library

// pin definition for the Uno#define sd_cs  4#define lcd_cs 10#define dc     9#define rst    8  

// pin definition for the Leonardo//#define sd_cs  8//#define lcd_cs 7//#define dc     0//#define rst    1  

TFT TFTscreen = TFT(lcd_cs, dc, rst);

// this variable represents the image to be drawn on screenPImage logo;

void setup() {  // initialize the GLCD and show a message  // asking the user to open the serial line  TFTscreen.begin();  TFTscreen.background(255, 255, 255);

  TFTscreen.stroke(0, 0, 255);  TFTscreen.println();  TFTscreen.println("Arduino TFT Bitmap Example");  TFTscreen.stroke(0, 0, 0);  TFTscreen.println("Open serial monitor");  TFTscreen.println("to run the sketch");

  // initialize the serial port: it will be used to   // print some diagnostic info    Serial.begin(9600);  while (!Serial) {    // wait for serial line to be ready  }

Page 181: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  // clear the GLCD screen before starting  TFTscreen.background(255, 255, 255);    // try to access the SD card. If that fails (e.g.  // no card present), the setup process will stop.  Serial.print("Initializing SD card...");  if (!SD.begin(sd_cs)) {    Serial.println("failed!");    return;  }  Serial.println("OK!");    // initialize and clear the GLCD screen  TFTscreen.begin();  TFTscreen.background(255, 255, 255);

  // now that the SD card can be access, try to load the  // image file.  logo = TFTscreen.loadImage("arduino.bmp");  if (!logo.isValid()) {    Serial.println("error while loading arduino.bmp");  }}

void loop() {  // don't do anything if the image wasn't loaded correctly.  if (logo.isValid() == false) {    return;  }    Serial.println("drawing image");

  // get a random location where to draw the image.  // To avoid the image to be draw outside the screen,  // take into account the image size.  int x = random(TFTscreen.width() - logo.width());  int y = random(TFTscreen.height() - logo.height());

  // draw the image to the screen  TFTscreen.image(logo, x, y);

  // wait a little bit before drawing again  delay(1500);}

TFT Display Text

This example demonstrates how to draw text on the Arduino GLCD screen when connected to an Arduino. The Arduino reads the value of an analog sensor attached to pin A0, and writes the value to the LCD screen, updating every quarter second.Hardware Required

Arduino Uno Arduino TFT screen breadboard hookup wire one 10-kilohm potentiometer

CircuitConnect power and ground to the breadboard. Show me how to do thatPlace the potentiometer on the breadboard. Connect one side to ground, and the other to power. Connect the middle pin to A0.Show me how to do thatConnect the screen to the breadboard. The headers on the side of the screen with the small blue tab and arrow should be the ones that attach to the board. Pay attention to the orientation of the screen, in these images, it is upside down. Show me how to do thatConnect the BL and +5V pins to power, and GND to ground. Connect CS-LD to pin 10, DC to pin 9, RESET to pin 8, MOSI to pin 13, and SCK to pin 11. If you're using a Leonardo, you'll be using different pins. see the getting started page for more details.Show me how to do that

Page 182: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

CodeTo use the screen you must first include the SPI and TFT libraries.#include <SPI.h>#include <TFT.h>

[Get Code]Define the pins you're going to use for controlling the screen, and create an instance of the TFT library namedTFTscreen. You'll reference that object whenever you're working with the screen.#define cs   10#define dc   9#define rst  8  

TFT TFTscreen = TFT(cs, dc, rst);[Get Code]

To update the screen with text, you'll need to store dynamic content in a char array.char sensorPrintout[4];In setup(), initialize the screen and clear the background. Set the color for the font with stroke(), and write any static text to the screen. In this case, you'll write "Sensor Value :". This will stay at the top of the screen and not change as long as the sketch runs. Before entering the loop(), set the text size so you can really see the sensor values stand out.void setup() {  TFTscreen.begin();

  TFTscreen.background(0, 0, 0);

  TFTscreen.stroke(255,255,255);  TFTscreen.setTextSize(2);  TFTscreen.text("Sensor Value : ",0,0);  TFTscreen.setTextSize(5);}

[Get Code]In loop(), read the value from the potentiometer and store it in a string. Convert the string content to a char array, storing it in the global array you declared int he beginning of your program.void loop() {

  String sensorVal = String(analogRead(A0));

  sensorVal.toCharArray(sensorPrintout, 4);[Get Code]

Set the text color (this would be a good place to change the color of the text depending on the value from the potentiometer), and print it to the screen below the static text.TFTscreen.stroke(255,255,255);  TFTscreen.text(sensorPrintout, 0, 20);

[Get Code]Wait a wuarter second second, then erase the text you just wrote, so you can update it in the next run through loop().delay(250);  TFTscreen.stroke(0,0,0);  TFTscreen.text(sensorPrintout, 0, 20);}

[Get Code]The complete sketch is below :/*  Arduino TFT text example    This example demonstrates how to draw text on the   TFT with an Arduino. The Arduino reads the value   of an analog sensor attached to pin A0, and writes   the value to the LCD screen, updating every  quarter second.     This example code is in the public domain

  Created 15 April 2013 by Scott Fitzgerald   http://arduino.cc/en/Tutorial/TFTDisplayText  */

#include <TFT.h>  // Arduino LCD library#include <SPI.h>

// pin definition for the Uno#define cs   10#define dc   9#define rst  8  

// pin definition for the Leonardo// #define cs   7// #define dc   0// #define rst  1 

// create an instance of the libraryTFT TFTscreen = TFT(cs, dc, rst);

// char array to print to the screenchar sensorPrintout[4];

void setup() {  

Page 183: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  // Put this line at the beginning of every sketch that uses the GLCD:  TFTscreen.begin();

  // clear the screen with a black background  TFTscreen.background(0, 0, 0);    // write the static text to the screen  // set the font color to white  TFTscreen.stroke(255,255,255);  // set the font size  TFTscreen.setTextSize(2);  // write the text to the top left corner of the screen  TFTscreen.text("Sensor Value :\n ",0,0);  // ste the font size very large for the loop  TFTscreen.setTextSize(5);}

void loop() {

  // Read the value of the sensor on A0  String sensorVal = String(analogRead(A0));   // convert the reading to a char array  sensorVal.toCharArray(sensorPrintout, 4);

  // set the font color  TFTscreen.stroke(255,255,255);  // print the sensor value  TFTscreen.text(sensorPrintout, 0, 20);  // wait for a moment  delay(250);  // erase the text you just wrote  TFTscreen.stroke(0,0,0);  TFTscreen.text(sensorPrintout, 0, 20);}

TFT Pong

This sketch is a basic implementation of pong for the TFT screen with an Arduino Uno.This version of the game creates a rectangular platform that can move in two directions, and a ball that bounces

against the edges of the screen as well as the movable platform. Two potentiometers (or other analog sensor) control the position of the platform.The example demonstrates collision detection between objects on the screen, as well as how to quickly update images without erasing the entire screen every loop()Hardware Required

Arduino Uno Arduino TFT screen breadboard hookup wire two 10-kilohm potentiometers

CircuitConnect power and ground to the breadboard. Show the circuitPlace the potentiometers on the breadboard. On each pot, connect one side to ground, and the other to power. Connect the middle pin of one potentiometer to A0, the other one to A1.Show the circuitConnect the TFT screen to the breadboard. The headers on the side of the screen with the small blue tab and arrow should be the ones that attach to the board. Pay attention to the orientation of the screen, in these images, it is upside down. Show the circuitConnect the BL and +5V pins to power, and GND to ground. Connect CS-LD to pin 10, DC to pin 9, RESET to pin 8, MOSI to pin 13, and SCK to pin 11. If uyou're using a Leonardo, you'll be using different pins. see the getting started page for more details.Show the circuitCodeTo use the screen you must first include the SPI and TFT libraries.#include <SPI.h>#include <TFT.h>

[Get Code]Define the pins you're going to use for controlling the screen, and create an instance of the TFT library

Page 184: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

namedTFTscreen. You'll reference that object whenever you're working with the screen.#define cs   10#define dc   9#define rst  8  

TFT TFTscreen = TFT(cs, dc, rst);[Get Code]

Set up the variables for the ball and paddle x & y positions, the ball's direction, and the previous locations of the ball and paddle.int paddleX = 0;int paddleY = 0;int oldPaddleX, oldPaddleY;int ballDirectionX = 1;int ballDirectionY = 1;

int ballX, ballY, oldBallX, oldBallY;[Get Code]

In setup(), initialize the display and clear the screen's background.void setup() {  TFTscreen.begin();  TFTscreen.background(0,0,0); }

[Get Code]loop() starts by storing the width and height of the screen, an reading the values of the potentiometers, before mapping them to a useful range.void loop() {  int myWidth = TFTscreen.width();  int myHeight = TFTscreen.height();

  paddleX = map(analogRead(A0), 512, -512, 0, myWidth) - 20/2;   paddleY = map(analogRead(A1), 512, -512, 0, myHeight) - 5/2;

[Get Code]Set the fill color to black, and erase the previous location of the paddle if it has moved.TFTscreen.fill(0,0,0);

  if (oldPaddleX != paddleX || oldPaddleY != paddleY) {    TFTscreen.rect(oldPaddleX, oldPaddleY, 20, 5);  }

[Get Code]Set the fill color to white, and draw the paddle.TFTscreen.fill(255,255,255);  TFTscreen.rect(paddleX, paddleY, 20, 5);

[Get Code]

Save the paddle's current location as the previous location, so the next time through you can check if it has moved.oldPaddleX = paddleX;  oldPaddleY = paddleY;

[Get Code]At the end of loop(), use the value of the ballSpeed variable to determine how quickly the display will update. Once you've finished with the example, you could add another potentiometer and change the speed dynamically by changing the value of ballSpeed.You'll call a custom function named moveBall() to update the ball's position.if (millis() % ballSpeed < 2) {  moveBall();  }}

[Get Code]moveBall() will update the ball's position, erase its previous location, and draw it in the new spot. It will also check to make sure it does not go off the screen, reversing direction when it hits the sides. This also calls a second custom function named inPaddle() which checks for intersections of the ball and paddle.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);

  if (oldBallX != ballX || oldBallY != ballY) {    TFTscreen.rect(oldBallX, oldBallY, 5, 5);  }

  TFTscreen.fill(255,255,255);  TFTscreen.rect(ballX, ballY, 5, 5);

  oldBallX = ballX;  oldBallY = ballY;}

[Get Code]

Page 185: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

inPaddle() checks to see if the paddle and ball occupy the same space. If so, it returns TRUE, which reverses the ball's direction in moveBall().boolean inPaddle(int x, int y, int rectX, int rectY, int rectWidth, int rectHeight) {  boolean result = false;

  if ((x >= rectX && x <= (rectX + rectWidth)) &&     (y >= rectY && y <= (rectY + rectHeight))) {    result = true;   }  return result;  }

TFT EtchASketch

This example for the Arduino TFT draws a white line on the screen, based on the position of 2 potentiometers. If you press a momentary button, the screen will erase.Hardware Required

Arduino Uno Arduino TFT screen breadboard hookup wire two 10-kilohm potentiometers momentary switch 10-kilohm resistor

CircuitConnect power and ground to the breadboard. Show me how to do thatPlace the potentiometers on the breadboard. On each pot, connect one side to ground, and the other to power. Connect the middle pin of one potentiometer to A0, the other one to A1.Show me how to do that

Put a switch across the center of the breadboard. Connect one end to power, the other end to the Arduino digital pin 2. Connect the same pin to ground through a 10-kilohm pull-down resistorShow me how to do thatConnect the screen to the breadboard. The headers on the side of the screen with the small blue tab and arrow should be the ones that attach to the board. Pay attention to the orientation of the screen, in these images, it is upside down. Show me how to do thatConnect 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 thatCodeTo use the screen you must first include the SPI and TFT libraries.#include <SPI.h>#include <TFT.h>

[Get Code]Define the pins you're going to use for controlling the screen, and create an instance of the TFT library namedTFTscreen. You'll reference that object whenever you're working with the screen.#define cs   10#define dc   9#define rst  8  

TFT TFTscreen = TFT(cs, dc, rst);[Get Code]

Set up the cursor's x & y position. In the example, it starts in the center of the screen; determined by dividing the height and width of the screen by 2. Create a named pin for your erase switch.int xPos = LCDscreen.width()/2;int yPos = LCDscreen.height()/2;

int erasePin = 2;[Get Code]

Page 186: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

In setup(), after declaring the erase pin as an input, initialize the display and clear the screen's background.void setup() {  pinMode(erasePin, INPUT);  TFTscreen.begin();  TFTscreen.background(0,0,0); }

[Get Code]Read the values of the pots and map them to smaller numbers.void loop(){  int xValue = analogRead(A0);  int yValue = analogRead(A1);

  xPos = xPos + (map(xValue, 0, 1023, 2, -2));  yPos = yPos + (map(yValue, 0, 1023, -2, 2));

[Get Code]You'll want to keep the cursor from moving offscreen with a few if() statements before you draw the point.if(xPos > 159){    (xPos = 159);  }

  if(xPos < 0){    (xPos = 0);  }  if(yPos > 127){    (yPos = 127);  }

  if(yPos < 0){    (yPos = 0);  }

  TFTscreen.stroke(255,255,255);  TFTscreen.point(xPos,yPos);

[Get Code]Finally, check the button. If it is being pressed and is HIGH, clear the screen with background().if(digitalRead(erasePin) == HIGH){    TFTscreen.background(0,0,0);  }

  delay(33);            }

TFT Color Picker

This example for the Arduino TFT screen reads the input of three analog sensors, using the values to change the screen's color.Color on the TFT screen is handled as 8-bit numbers (0-255). However, the library scales these values to 5-bits (32 levels) for red and blue, 6-bits (64 levels) for green.Hardware Required

Arduino Uno Arduino TFT screen breadboard hookup wire three 10-kilohm potentiometers

CircuitConnect power and ground to the breadboard. Show me how to do thatAttach the three pots to the breadboard, connecting their outside legs to power and ground. the center legs should connect to A0-A2. Show me how to do thatConnect the LCD screen to the breadboard. The headers on the side of the screen with the small blue tab and arrow should be the ones that attach to the board. Pay attention to the orientation of the screen, in these images, it is upside down. Show me how to do thatConnect the BL and +5V pins to power, and GND to ground. Connect CS-LD to pin 10, DC to pin 9, RESET to pin 8, MOSI to pin 13, and SCK to pin 11. If you're using a Leonardo, you'll be using different pins. see the getting started

Page 187: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

page for more details.Show me how to do thatCodeTo use the screen you must first include the SPI and TFT libraries.#include <SPI.h>#include <TFT.h>

[Get Code]Define the pins you're going to use for controlling the screen, and create an instance of the TFT library namedTFTscreen. You'll reference that object whenever you're working with the screen.#define cs   10#define dc   9#define rst  8  

TFT TFTscreen = TFT(cs, dc, rst);[Get Code]

In setup(), initialize the screen and clear the background. Start serial communication as well.void setup() {  Serial.begin(9600);  TFTscreen.begin();  TFTscreen.background(255, 255, 255);}

[Get Code]In loop(), read the values fron the pots, mapping them to values between 0-255. with background(), set the mapped background colors and print the values to the serial monitor.void loop() {

  int redVal = map(analogRead(A0), 0, 1023, 0, 255);   int greenVal = map(analogRead(A1), 0, 1023, 0, 255);   int blueVal = map(analogRead(A2), 0, 1023, 0, 255);

  TFTscreen.background(redVal, greenVal, blueVal);

  Serial.print("background(");  Serial.print(redVal);  Serial.print(" , ");  Serial.print(greenVal);  Serial.print(" , ");  Serial.print(blueVal);  Serial.println(")");

  delay(33);

}[Get Code]

The complete sketch is below :/*

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

Page 188: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  // draw the background based on the mapped values  TFTscreen.background(redVal, greenVal, blueVal);    // send the values to the serial monitor  Serial.print("background(");  Serial.print(redVal);  Serial.print(" , ");  Serial.print(greenVal);  Serial.print(" , ");  Serial.print(blueVal);  Serial.println(")");    // wait for a moment  delay(33);

}

TFT Graph

This example for the Arduino TFT screen reads the value of a potentiometer, and graphs it on screen. This is similar to the serial communication Graph example.Hardware Required

Arduino Uno Arduino TFT screen breadboard hookup wire one 10-kilohm potentiometer

CircuitConnect power and ground to the breadboard. Show me how to do thatPlace the potentiometer on the breadboard. Connect one side to ground, and the other to power. Connect the middle pin to A0.Show me how to do that

Connect the TFT screen to the breadboard. The headers on the side of the screen with the small blue tab and arrow should be the ones that attach to the board. Pay attention to the orientation of the screen, in these images, it is upside down. Show me how to do thatConnect the BL and +5V pins to power, and GND to ground. Connect CS-LD to pin 10, DC to pin 9, RESET to pin 8, MOSI to pin 13, and SCK to pin 11. If you're using a Leonardo, you'll be using different pins. see the getting started page for more details.Show me how to do thatCodeTo use the screen you must first include the SPI and TFT libraries.#include <SPI.h>#include <TFT.h>

[Get Code]Define the pins you're going to use for controlling the screen, and create an instance of the TFT library namedTFTscreen. You'll reference that object whenever you're working with the screen.#define cs   10#define dc   9#define rst  8  

TFT TFTscreen = TFT(cs, dc, rst);[Get Code]

Create a variable for holding the position of the x-axis of the graph. You'll increment this each loop(). In setup(), initialize the screen and make the background a nice color.int xPos = 0;

void setup(){  TFTscreen.begin();  TFTscreen.background(250,16,200); }

[Get Code]In loop(), read the value from the potentiometer, and map it to a value that fits in the screen's height.void loop(){  int sensor = analogRead(A0);  int graphHeight = map(sensor,0,1023,0,LCDscreen.height());

[Get Code]

Page 189: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Set the stroke color to something that will stand out against the nice color you chose for the background, and draw a line from the bottom of the screen based on the value of the sensorTFTscreen.stroke(250,180,10);  TFTscreen.line(xPos, TFTscreen.height() - graphHeight, xPos, TFTscreen.height());

[Get Code]Before closing up loop(), check to make sure the graph hasn't gone past the edge of the screen. If it has, erase everything, and start back at 0 on the x-axis.if (xPos >= 160) {    xPos = 0;    TFTscreen.background(250,16,200);   }   else {    xPos++;  }  delay(16);}

[Get Code]The complete sketch is below :/*

 TFT Graph  This example for an Arduino screen reads   the value of an analog sensor on A0, and  graphs the values on the screen.  This example code is in the public domain.  Created 15 April 2013 by Scott Fitzgerald  http://arduino.cc/en/Tutorial/TFTGraph  */

#include <TFT.h>  // Arduino LCD library#include <SPI.h>  // pin definition for the Uno#define cs   10#define dc   9#define rst  8  

// pin definition for the Leonardo// #define cs   7// #define dc   0// #define rst  1 

TFT TFTscreen = TFT(cs, dc, rst);

// position of the line on screenint xPos = 0;

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

  // initialize the display  TFTscreen.begin();

  // clear the screen with a pretty color  TFTscreen.background(250,16,200); }

void loop(){  // read the sensor and map it to the screen height  int sensor = analogRead(A0);  int drawHeight = map(sensor,0,1023,0,TFTscreen.height());    // print out the height to the serial monitor  Serial.println(drawHeight);    // draw a line in a nice color  TFTscreen.stroke(250,180,10);  TFTscreen.line(xPos, TFTscreen.height()-drawHeight, xPos, TFTscreen.height());

  // if the graph has reached the screen edge  // erase the screen and start again  if (xPos >= 160) {    xPos = 0;    TFTscreen.background(250,16,200);   }   else {    // increment the horizontal position:    xPos++;  }

  delay(16);}

WiFi libraryThe firmware for the WiFi shield has changed in Arduino IDE 1.0.5. You are recommended to install this update per  these instructionsWith 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.

Page 190: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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 classThe WiFi class initializes the ethernet library and network settings.

begin() disconnect() config() setDNS() SSID() BSSID() RSSI() encryptionType() scanNetworks() getSocket() macAddress()

IPAddress classThe IPAddress class provides information about the network configuration.

localIP() subnetMask() gatewayIP()

Server classThe 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 classThe 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 classThe 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()DescriptionInitializes the WiFi library's network settings and provides the current status.SyntaxWiFi.begin(); WiFi.begin(ssid); WiFi.begin(ssid, pass); WiFi.begin(ssid, keyIndex, key); Parametersssid: 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

Page 191: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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 onExample#include <WiFi.h>

//SSID of your network char ssid[] = "yourNetwork";//password of your WPA Network char pass[] = "secretPassword";

void setup(){ WiFi.begin(ssid, pass);}

void loop () {}

WiFi.disconnect()DescriptionDisconnects the WiFi shield from the current network.SyntaxWiFi.disconnect(); Parametersnone

WiFi.config()DescriptionWiFi.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() forces 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.SyntaxWiFi.config(ip); WiFi.config(ip, dns); WiFi.config(ip, dns, gateway); WiFi.config(ip, dns, gateway, subnet); Parametersip: 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 1subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0ReturnsNothingExampleThis example shows how to set the static IP address, 192.168.0.177, of the LAN network to the WiFi shield:#include <SPI.h>#include <WiFi.h>

// the IP address for the shield:IPAddress ip(192, 168, 0, 177);    

char ssid[] = "yourNetwork";    // your network SSID (name) char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP)

int status = WL_IDLE_STATUS;

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

  // check for the presence of the shield:  if (WiFi.status() == WL_NO_SHIELD) {    Serial.println("WiFi shield not present"); 

Page 192: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    while(true);  // don't continue  } 

  WiFi.config(ip);

  // attempt to connect to Wifi network:  while ( status != WL_CONNECTED) {     Serial.print("Attempting to connect to SSID: ");    Serial.println(ssid);    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:        status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:    delay(10000);  }

  // print your WiFi shield's IP address:  Serial.print("IP Address: ");  Serial.println(WiFi.localIP()); }

void loop () {}

WiFi.config()DescriptionWiFi.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() forces 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.SyntaxWiFi.config(ip); WiFi.config(ip, dns); WiFi.config(ip, dns, gateway); WiFi.config(ip, dns, gateway, subnet); Parametersip: 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 1subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0ReturnsNothingExampleThis example shows how to set the static IP address, 192.168.0.177, of the LAN network to the WiFi shield:#include <SPI.h>#include <WiFi.h>

// the IP address for the shield:IPAddress ip(192, 168, 0, 177);    

char ssid[] = "yourNetwork";    // your network SSID (name) char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP)

int status = WL_IDLE_STATUS;

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

  // check for the presence of the shield:  if (WiFi.status() == WL_NO_SHIELD) {    Serial.println("WiFi shield not present");     while(true);  // don't continue  } 

  WiFi.config(ip);

  // attempt to connect to Wifi network:  while ( status != WL_CONNECTED) {     Serial.print("Attempting to connect to SSID: ");    Serial.println(ssid);    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:        status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:    delay(10000);  }

  // print your WiFi shield's IP address:  Serial.print("IP Address: ");  Serial.println(WiFi.localIP()); }

Page 193: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

void loop () {}

WiFi.setDNS()DescriptionWiFi.setDNS() allows you to configure the DNS (Domain Name System) server.SyntaxWiFi.setDNS(dns_server1)WiFi.setDNS(dns_server1, dns_server2)Parametersdns_server1: the IP address of the primary DNS serverdns_server2: the IP address of the secondary DNS serverReturnsNothingExampleThis 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()DescriptionGets the SSID of the current networkSyntaxWiFi.SSID(); WiFi.SSID(wifiAccessPoint)ParameterswifiAccessPoint: specifies from which network to get the informationReturnsA 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;     // the Wifi radio's status

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 () {}

Page 194: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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()DescriptionGets the signal strength of the connection to the routerSyntaxWiFi.RSSI(); WiFi.RSSI(wifiAccessPoint);ParameterswifiAccessPoint: specifies from which network to get the informationReturnslong : the current RSSI /Received Signal Strength in dBmExample#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 () {}

WiFi.RSSI()DescriptionGets the signal strength of the connection to the routerSyntaxWiFi.RSSI(); WiFi.RSSI(wifiAccessPoint);ParameterswifiAccessPoint: specifies from which network to get the informationReturnslong : the current RSSI /Received Signal Strength in dBmExample#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 () {}

WiFi.scanNetworks()DescriptionScans for available WiFi networks and returns the discovered numberSyntaxWiFi.scanNetworks(); Parametersnone

Page 195: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Returnsbyte : number of discovered networksExample#include <SPI.h>#include <WiFi.h>

char ssid[] = "yourNetwork";     // the name of your networkint status = WL_IDLE_STATUS;     // the Wifi radio's status

byte mac[6];                     // the MAC address of your Wifi shield

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 {

  Serial.println("** Scan Networks **");  byte numSsid = WiFi.scanNetworks();

  Serial.print("SSID List:");  Serial.println(numSsid);  }}

void loop () {}

WiFi.getSocket()Descriptiongets the first socket availableSyntaxWiFi.getSocket(); ParametersnoneReturnsint : the first socket available

WiFi.macAddress()DescriptionGets the MAC Address of your WiFi shieldSyntaxWiFi.macAddress(mac); 

Parametersmac: a 6 byte array to hold the MAC addressReturnsbyte array : 6 bytes representing the MAC address of your shieldExample#include <SPI.h>#include <WiFi.h>

char ssid[] = "yourNetwork";     // the name of your networkint status = WL_IDLE_STATUS;     // the Wifi radio's status

byte mac[6];                     // the MAC address of your Wifi shield

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()DescriptionGets the WiFi shield's IP addressSyntaxWiFi.localIP(); Parametersnone

Page 196: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Returnsthe IP address of the shieldExample

#include <WiFi.h>

char ssid[] = "yourNetwork";      //SSID of your network

int status = WL_IDLE_STATUS;     // the Wifi radio's status

IPAddress ip;                    // the IP address of your shield

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

 WiFi.begin(ssid);

  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()DescriptionGets the WiFi shield's subnet maskSyntaxWiFi.subnet(); ParametersnoneReturnsthe subnet mask of the shieldExample#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 ip;

IPAddress subnet;IPAddress gateway;

void setup(){  WiFi.begin(ssid, pass);

  if ( status != WL_CONNECTED) {     Serial.println("Couldn't get a wifi connection");    while(true);  }   // if you are connected, print out info about the connection:  else {

    // print your subnet mask:    subnet = WiFi.subnetMask();    Serial.print("NETMASK: ");    Serial.println();

  }}

void loop () {}

WiFi.gatewayIP()DescriptionGets the WiFi shield's gateway IP address.SyntaxWiFi.gatewayIP(); ParametersnoneReturnsAn array containing the shield's gateway IP addressExample(: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:

Page 197: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

else { // print your gateway address: gateway = WiFi.gatewayIP(); Serial.print("GATEWAY: "); Serial.println(gateway); }}void loop () {} (:sourceend:)

ServerDescriptionServer 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()DescriptionCreates a server that listens for incoming connections on the specified port.SyntaxServer(port);Parametersport: the port to listen on (int)ReturnsNoneExample#include <SPI.h>#include <WiFi.h>

char ssid[] = "myNetwork";          //  your network SSID (name) char pass[] = "myPassword";   // your network passwordint 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() {

}

begin()DescriptionTells the server to begin listening for incoming connections.Syntaxserver.begin()ParametersNoneReturnsNoneExample#include <SPI.h>#include <WiFi.h>

char ssid[] = "lamaison";          //  your network SSID (name) char pass[] = "tenantaccess247";   // your network passwordint 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() {

}

Page 198: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

available()DescriptionGets 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.Syntaxserver.available()ParametersNoneReturnsa Client object; if no Client has data available for reading, this object will evaluate to false in an if-statementExample#include <SPI.h>#include <WiFi.h>

char ssid[] = "Network";          //  your network SSID (name) char pass[] = "myPassword";   // your network passwordint 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()DescriptionWrite data to all the clients connected to a server.Syntaxserver.write(data)Parametersdata: the value to write (byte or char)Returnsbyte : 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());  }}

Page 199: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

print()DescriptionPrint 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').Syntaxserver.print(data) server.print(data, BASE)Parametersdata: 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).Returnsbyte print() will return the number of bytes written, though reading that number is optional

println()DescriptionPrints 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').Syntaxserver.println() server.println(data) server.println(data, BASE)Parametersdata (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).Returnsbyteprintln() will return the number of bytes written, though reading that number is optional

Client()

DescriptionClient 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()DescriptionCreates a client that can connect to to a specified internet IP address and port as defined in client.connect().SyntaxWiFiClient()ParametersnoneExample#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 libraryWiFiClient 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();    }  }}

Page 200: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

void loop() {

}

connected()DescriptionWhether 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.Syntaxclient.connected()ParametersnoneReturnsReturns 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 libraryWiFiClient 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()DescriptionConnect 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).Syntaxclient.connect(ip, port)client.connect(URL, port)Parametersip: 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)ReturnsReturns 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...");

Page 201: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  Serial.print("SSID: ");  Serial.println(ssid);

  status = WiFi.begin(ssid, pass);  if ( status != WL_CONNECTED) {     Serial.println("Couldn't get a wifi connection");    // don't do anything else:    while(true);  }   else {    Serial.println("Connected to wifi");    Serial.println("\nStarting connection...");    // if you get a connection, report back via serial:    if (client.connect(servername, 80)) {      Serial.println("connected");      // Make a HTTP request:      client.println("GET /search?q=arduino HTTP/1.0");      client.println();    }  }}

void loop() {

}

write()DescriptionWrite data to the server the client is connected to.Syntaxclient.write(data)Parametersdata: the byte or char to writeReturnsbyte: the number of characters written. it is not necessary to read this value.

print()DescriptionPrint 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').Syntaxclient.print(data) client.print(data, BASE)Parametersdata: 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).Returnsbyte : returns the number of bytes written, though reading that number is optional 

println()DescriptionPrint 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').Syntaxclient.println() client.println(data) client.print(data, BASE)Parametersdata (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).Returnsbyte: return the number of bytes written, though reading that number is optional

available()DescriptionReturns 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.Syntaxclient.available()ParametersnoneReturnsThe number of bytes available.Example#include <SPI.h>#include <WiFi.h>

char ssid[] = "myNetwork";          //  your network SSID (name) 

Page 202: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

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

  // if the server's disconnected, stop the client:  if (!client.connected()) {    Serial.println();    Serial.println("disconnecting.");    client.stop();

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

read()Read the next byte received from the server the client is connected to (after the last call to read()).

read() inherits from the Stream utility class.Syntaxclient.read()ParametersnoneReturnsThe 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.flush() inherits from the Stream utility class.Syntaxclient.flush()ParametersnoneReturnsnone

stop()Disconnect from the serverSyntaxclient.stop()ParametersnoneReturnsnone

WiFiUDPDescriptionCreates a named instance of the WiFi UDP class that can send and receive UDP messages.SyntaxWiFiUDPParametersnone

WiFi : WiFiUDP.begin()DescriptionInitializes the WiFi UDP library and network settings. Starts WiFiUDP socket, listening at local port PORT */SyntaxWiFiUDP.begin(port); 

Page 203: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Parametersport: the local port to listen on (int)Returns

1: if successful 0: if there are no sockets available to

use

WiFi : WiFiUDP.available()available()DescriptionGet the number of bytes (characters) available for reading from the buffer. This is data that's already arrived.This function can only be successfully called after WiFiUDP.parsePacket().available() inherits from the Stream utility class.SyntaxWiFiUDP.available()ParametersNoneReturns

the number of bytes available in the current packet

0: if parsePacket hasn't been called yet

WiFi : WiFiUDP.beginPacket()DescriptionStarts a connection to write UDP data to the remote connectionSyntaxWiFiUDP.beginPacket(hostName, port); WiFiUDP.beginPacket(hostIp, port);ParametershostName: the address of the remote host. It accepts a character string or an IPAddresshostIp: the IP address of the remote connection (4 bytes)port: the port of the remote connection (int)Returns

1: if successful 0: if there was a problem with the

supplied IP address or port

WiFi : WiFiUDP.endPacket()

DescriptionCalled after writing UDP data to the remote connection. It finishes off the packet and send it.SyntaxWiFiUDP.endPacket(); ParametersNoneReturns

1: if the packet was sent successfully 0: if there was an error

WiFi : WiFiUDP.write()DescriptionWrites 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.SyntaxWiFiUDP.write(byte);WiFiUDP.write(buffer, size);Parametersbyte: the outgoing bytebuffer: the outgoing messagesize: the size of the buffer Returns

single byte into the packet bytes size from buffer into the packet

WiFi : WiFiUDP.parsePacket()DescriptionIt 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().SyntaxUDP.parsePacket(); ParametersNoneReturns

the size of the packet in bytes 0: if no packets are available

WiFi : WiFiUDP.peek()peek()

Page 204: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

Read a byte from the file without advancing to the next one. That is, successive calls to peek() will return the same value, as will the next call to read().This function inherited from the Stream class. See the Stream class main page for more information.SyntaxWiFiUDP.peek()ParametersnoneReturns

b: the next byte or character -1: if none is available

WiFi : WiFiUDP.read()DescriptionReads 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().SyntaxWiFiUDP.read();WiFiUDP.read(buffer, len); Parametersbuffer: 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

flush()Discard any bytes that have been written to the client but not yet read.flush() inherits from the Stream utility class.SyntaxWiFiUDP.flush()ParametersnoneReturnsnone

stop()

DescriptionDisconnect from the server. Release any resource being used during the UDP session.SyntaxWiFiUDP.stop()ParametersnoneReturnsnone

WiFi : WiFiUDP.remoteIP()DescriptionGets the IP address of the remote connection.This function must be called after WiFiUDP.parsePacket().SyntaxWiFiUDP.remoteIP(); ParametersNoneReturns4 bytes : the IP address of the host who sent the current incoming packet

WiFi : WiFIUDP.remotePort()DescriptionGets the port of the remote UDP connection.This function must be called after UDP.parsePacket().SyntaxUDP.remotePort(); ParametersNoneReturnsThe port of the host who sent the current incoming packet

Connect No EncryptionThis 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

Page 205: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

The WiFi shield uses pins 10, 11, 12, and 13 for the SPI connection to the HDG104 module. Digital pin 4 is used to control the slave select pin on the SD card.You should have access to a 802.11b/g wireless network that connects to the internet for this example. You will need to change the network settings in the sketch to correspond to your particular networks SSID.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*  This example connects to an unencrypted Wifi network.  Then it prints the  MAC address of the Wifi shield,  the IP address obtained, and other network details.

 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 networkint 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 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(":");

Page 206: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  Serial.println(mac[0],HEX);    // print your subnet mask:  IPAddress subnet = WiFi.subnetMask();  Serial.print("NetMask: ");  Serial.println(subnet);

  // print your gateway address:  IPAddress gateway = WiFi.gatewayIP();  Serial.print("Gateway: ");  Serial.println(gateway);}

void printCurrentNet() {  // print the SSID of the network you're attached to:  Serial.print("SSID: ");  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to:  byte bssid[6];  WiFi.BSSID(bssid);      Serial.print("BSSID: ");  Serial.print(bssid[5],HEX);  Serial.print(":");  Serial.print(bssid[4],HEX);  Serial.print(":");  Serial.print(bssid[3],HEX);  Serial.print(":");  Serial.print(bssid[2],HEX);  Serial.print(":");  Serial.print(bssid[1],HEX);  Serial.print(":");  Serial.println(bssid[0],HEX);

  // print the received signal strength:  long rssi = WiFi.RSSI();  Serial.print("signal strength (RSSI):");  Serial.println(rssi);

  // print the encryption type:  byte encryption = WiFi.encryptionType();  Serial.print("Encryption Type:");  Serial.println(encryption,HEX);}

Connect With WEPThis example shows you how to connect to a WEP encrypted 802.11b/g network with the Arduino WiFi shield. Your Arduino's serial monitor will provide information about the connection once it has connected.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board

Circuit

The WiFi shield uses pins 10, 11, 12, and 13 for the SPI connection to the HDG104 module. Digital pin 4 is used to control the slave select pin on the SD card.You should have access to a 802.11b/g wireless network that connects to the internet for this example. You will need to change the network settings in the sketch to correspond to your particular networks SSID.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.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*  This example connects to a WEP-encrypted Wifi network.  Then it prints the  MAC address of the Wifi shield,  the IP address obtained, and other network details.   If you use 40-bit WEP, you need a key that is 10 characters long,  and the characters must be hexadecimal (0-9 or A-F). 

Page 207: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

 e.g.   for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work  (too short) and ABBAISDEAF won't work (I and S are not  hexadecimal characters).   For 128-bit, you need a string that is 26 characters long.  D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters,  all in the 0-9, A-F range.  Circuit: * WiFi shield attached  created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 by Tom Igoe */#include <WiFi.h>

char ssid[] = "yourNetwork";                     // your network SSID (name) char key[] = "D0D0DEADF00DABBADEAFBEADED";       // your network keyint keyIndex = 0;                                // your network key Index numberint status = WL_IDLE_STATUS;                     // the Wifi radio's status

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

  // check for the presence of the shield:  if (WiFi.status() == WL_NO_SHIELD) {    Serial.println("WiFi shield not present");     // don't continue:    while(true);  } 

  // attempt to connect to Wifi network:  while ( status != WL_CONNECTED) {     Serial.print("Attempting to connect to WEP network, SSID: ");    Serial.println(ssid);    status = WiFi.begin(ssid, keyIndex, key);

    // wait 10 seconds for connection:    delay(10000);  }

  // once you are connected :  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);}

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

Page 208: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  Serial.print("Encryption Type:");  Serial.println(encryption,HEX);  Serial.println();}

Connect With WPAThis example shows you how to connect to a WPA2 Personal encrypted 802.11b/g network with the Arduino WiFi shield. Your Arduino's serial monitor will provide information about the connection once it has connected.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*  This example connects to an unencrypted Wifi network.  Then it prints the  MAC address of the Wifi shield,  the IP address obtained, and other network details.

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

Page 209: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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

void printCurrentNet() {  // print the SSID of the network you're attached to:  Serial.print("SSID: ");  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to:  byte bssid[6];  WiFi.BSSID(bssid);      Serial.print("BSSID: ");  Serial.print(bssid[5],HEX);  Serial.print(":");  Serial.print(bssid[4],HEX);  Serial.print(":");  Serial.print(bssid[3],HEX);  Serial.print(":");  Serial.print(bssid[2],HEX);  Serial.print(":");  Serial.print(bssid[1],HEX);  Serial.print(":");  Serial.println(bssid[0],HEX);

  // print the received signal strength:  long rssi = WiFi.RSSI();  Serial.print("signal strength (RSSI):");

  Serial.println(rssi);

  // print the encryption type:  byte encryption = WiFi.encryptionType();  Serial.print("Encryption Type:");  Serial.println(encryption,HEX);  Serial.println();}

Connect With WPAThis example scans for 802.11b/g networks with the Arduino WiFi shield. Your Arduino's serial monitor will print out information about the board and the networks it can see. It will not connect to a network.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board

CircuitThe WiFi shield uses pins 10, 11, 12, and 13 for the SPI connection to the HDG104 module. Digital pin 4 is used to control the slave select pin on the SD card.Open your serial monitor to view the networks the WiFi shield can see. The Arduino may not see as many networks as your computer.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/* 

Page 210: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

 This example  prints the Wifi shield's MAC address, and scans for available Wifi networks using the Wifi shield. Every ten seconds, it scans again. It doesn't actually  connect to any network, so no encryption scheme is specified.  Circuit: * WiFi shield attached  created 13 July 2010 by dlf (Metodo2 srl) modified 21 Junn 2012 by Tom Igoe and Jaymes Dec */

#include <SPI.h>#include <WiFi.h>

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

  // check for the presence of the shield:  if (WiFi.status() == WL_NO_SHIELD) {    Serial.println("WiFi shield not present");     // don't continue:    while(true);  } 

  // Print WiFi MAC address:  printMacAddress();

  // scan for existing networks:  Serial.println("Scanning available networks...");  listNetworks();}

void loop() {  delay(10000);  // scan for existing networks:  Serial.println("Scanning available networks...");  listNetworks();}

void printMacAddress() {  // the MAC address of your Wifi shield  byte mac[6];                     

  // print your MAC address:  WiFi.macAddress(mac);  Serial.print("MAC: ");  Serial.print(mac[5],HEX);  Serial.print(":");  Serial.print(mac[4],HEX);

  Serial.print(":");  Serial.print(mac[3],HEX);  Serial.print(":");  Serial.print(mac[2],HEX);  Serial.print(":");  Serial.print(mac[1],HEX);  Serial.print(":");  Serial.println(mac[0],HEX);}

void listNetworks() {  // scan for nearby networks:  Serial.println("** Scan Networks **");  int numSsid = WiFi.scanNetworks();  if (numSsid == -1)  {     Serial.println("Couldn't get a wifi connection");    while(true);  } 

  // print the list of networks seen:  Serial.print("number of available networks:");  Serial.println(numSsid);

  // print the network number and name for each network found:  for (int thisNet = 0; thisNet<numSsid; thisNet++) {    Serial.print(thisNet);    Serial.print(") ");    Serial.print(WiFi.SSID(thisNet));    Serial.print("\tSignal: ");    Serial.print(WiFi.RSSI(thisNet));    Serial.print(" dBm");    Serial.print("\tEncryption: ");    printEncryptionType(WiFi.encryptionType(thisNet));  }}

void printEncryptionType(int thisType) {  // read the encryption type and print out the name:  switch (thisType) {  case ENC_TYPE_WEP:    Serial.println("WEP");    break;  case ENC_TYPE_TKIP:    Serial.println("WPA");    break;  case ENC_TYPE_CCMP:    Serial.println("WPA2");    break;  case ENC_TYPE_NONE:    Serial.println("None");    break;  case ENC_TYPE_AUTO:    Serial.println("Auto");    break;  } }

Page 211: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

WiFi Chat ServerA simple server that distributes any incoming messages to all connected clients. To use, open a terminal window, telnet to your WiFi shield's IP address, and type away. Any incoming text will be sent to all connected clients (including the one typing). Additionally, you will be able to see the client's input in your serial monitor as well.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/* Chat  Server  A simple server that distributes any incoming messages to all connected clients.  To use telnet to  your device's IP address and type. You can see the client's input in the serial monitor as well.  This example is written for a network using WPA encryption. For  WEP or WPA, change the Wifi.begin() call accordingly.   Circuit: * WiFi shield attached  created 18 Dec 2009 by David A. Mellis modified 31 May 2012 by Tom Igoe  */

#include <SPI.h>#include <WiFi.h>

char ssid[] = "yourNetwork"; //  your network SSID (name) char pass[] = "secretPassword";    // your network password (use for WPA, or use as key for WEP)

Page 212: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

WiFiServer server(23);

boolean alreadyConnected = false; // whether or not the client was connected previously

void setup() {  //Initialize serial and wait for port to open:  Serial.begin(9600);   while (!Serial) {    ; // wait for serial port to connect. Needed for Leonardo only  }    // check for the presence of the shield:  if (WiFi.status() == WL_NO_SHIELD) {    Serial.println("WiFi shield not present");     // don't continue:    while(true);  }     // attempt to connect to Wifi network:  while ( status != WL_CONNECTED) {     Serial.print("Attempting to connect to SSID: ");    Serial.println(ssid);    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:        status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:    delay(10000);  }   // start the server:  server.begin();  // you're connected now, so print out the status:  printWifiStatus(); }

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

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

    if (client.available() > 0) {      // read the bytes incoming from the client:      char thisChar = client.read();

      // echo the bytes back to the client:      server.write(thisChar);      // echo the bytes to the server as well:      Serial.write(thisChar);    }  }}

void printWifiStatus() {  // print the SSID of the network you're attached to:  Serial.print("SSID: ");  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:  IPAddress ip = WiFi.localIP();  Serial.print("IP Address: ");  Serial.println(ip);

  // print the received signal strength:  long rssi = WiFi.RSSI();  Serial.print("signal strength (RSSI):");  Serial.print(rssi);  Serial.println(" dBm");}

WiFi Xively ClientThis example shows you how to answer a HTTP request using a WiFi shield. Specifically, it connects to xively.com, a free datalogging site. The example requires that you set up a xively.com account, as well as a xively feed (for more information on setting up an input feed, please click here). Your WiFi shield will then connect to that feed and upload sensor data every 10 seconds.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board One analog sensor to attached

to AnalogIn pin 0Software Required

xively.com account xively.com feed that accepts two data

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

Page 213: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.

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

In the above image, the Arduino would be stacked below the WiFi shield.Code:/*  Wifi Xively sensor client  This sketch connects an analog sensor to Xively (http://www.xively.com) using an Arduino Wifi shield.

 This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.  This example has been updated to use version 2.0 of the Xively API.  To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed.

 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;

// initialize the library instance:WiFiClient client;// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server:IPAddress server(216,52,233,121);      // numeric IP for api.xively.com//char server[] = "api.xively.com";   // name

Page 214: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

address for xively API

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in millisecondsboolean lastConnected = false;                 // state of the connection last time through the main loopconst unsigned long postingInterval = 10*1000; //delay between updates to xively.com

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

  // check for the presence of the shield:  if (WiFi.status() == WL_NO_SHIELD) {    Serial.println("WiFi shield not present");    // don't continue:    while (true);  }

  String fv = WiFi.firmwareVersion();  if ( fv != "1.1.0" )    Serial.println("Please upgrade the firmware");

  // attempt to connect to Wifi network:  while ( status != WL_CONNECTED) {    Serial.print("Attempting to connect to SSID: ");    Serial.println(ssid);    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:    delay(10000);  }  // you're connected now, so print out the status:  printWifiStatus();}

void loop() {  // read the analog sensor:  int sensorReading = analogRead(A0);

  // if there's incoming data from the net connection.  // send it out the serial port.  This is for debugging  // purposes only:  while (client.available()) {    char c = client.read();    Serial.print(c);  }

  // if there's no net connection, but there was one last time

  // through the loop, then stop the client:  if (!client.connected() && lastConnected) {    Serial.println();    Serial.println("disconnecting.");    client.stop();  }

  // if you're not connected, and ten seconds have passed since  // your last connection, then connect again and send data:  if (!client.connected() && (millis() - lastConnectionTime > postingInterval)) {    sendData(sensorReading);  }  // store the state of the connection for next time through  // the loop:  lastConnected = client.connected();}

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

    // calculate the length of the sensor reading in bytes:    // 8 bytes for "sensor1," + number of digits of the data:    int thisLength = 8 + getLength(thisData);    client.println(thisLength);

    // last pieces of the HTTP PUT request:    client.println("Content-Type: text/csv");    client.println("Connection: close");    client.println();

    // here's the actual content of the PUT request:    client.print("sensor1,");    client.println(thisData);

  }  else {    // if you couldn't make a connection:    Serial.println("connection failed");    Serial.println();    Serial.println("disconnecting.");    client.stop();

Page 215: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  }  // note the time that the connection was made or attempted:  lastConnectionTime = millis();}

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

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

void printWifiStatus() {  // print the SSID of the network you're attached to:  Serial.print("SSID: ");  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:  IPAddress ip = WiFi.localIP();  Serial.print("IP Address: ");  Serial.println(ip);

  // print the received signal strength:  long rssi = WiFi.RSSI();  Serial.print("signal strength (RSSI):");  Serial.print(rssi);  Serial.println(" dBm");}

WiFi Xively Client StringThis example shows you how to answer a HTTP request using a WiFi shield. Specifically, it connects to xively.com, a free datalogging site. The example requires that you set up a xively.com account, as well as a xively feed (for more information on setting up an input feed, please click here). Your WiFi shield will then connect to

that feed and upload sensor data every 10 seconds.Additionally, this example shows how to send sensor data as a string.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board One analog sensor to attached

to AnalogIn pin 0Software Required

xively.com account xively.com feed that accepts two data

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

Page 216: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*  Wifi Xively sensor client with Strings  This sketch connects an analog sensor to Xively (http://www.xively.com) using a Arduino Wifi shield.

 This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.  This example has been updated to use version 2.0 of the xively.com API.  To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed.

 This example uses the String library, which is part of the Arduino core from version 0019.

 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>

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

// initialize the library instance:WiFiClient client;

// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server://IPAddress server(216,52,233,121);       // numeric IP for api.xively.comchar server[] = "api.xively.com";   // name address for xively API

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in millisecondsboolean lastConnected = false;                 // state of the connection last time through the main loopconst 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

Page 217: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  }

  // check for the presence of the shield:  if (WiFi.status() == WL_NO_SHIELD) {    Serial.println("WiFi shield not present");    // don't continue:    while (true);  }

  String fv = WiFi.firmwareVersion();  if ( fv != "1.1.0" )    Serial.println("Please upgrade the firmware");

  // attempt to connect to Wifi network:  while ( status != WL_CONNECTED) {    Serial.print("Attempting to connect to SSID: ");    Serial.println(ssid);    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:    delay(10000);  }  // you're connected now, so print out the status:  printWifiStatus();}

void loop() {  // read the analog sensor:  int sensorReading = analogRead(A0);  // convert the data to a String to send it:

  String dataString = "sensor1,";  dataString += sensorReading;

  // you can append multiple readings to this String if your  // xively feed is set up to handle multiple values:  int otherSensorReading = analogRead(A1);  dataString += "\nsensor2,";  dataString += otherSensorReading;

  // if there's incoming data from the net connection.  // send it out the serial port.  This is for debugging  // purposes only:  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(dataString);  }  // store the state of the connection for next time through  // the loop:  lastConnected = client.connected();}

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

    // last pieces of the HTTP PUT request:    client.println("Content-Type: text/csv");    client.println("Connection: close");    client.println();

    // here's the actual content of the PUT request:    client.println(thisData);  }  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:

Page 218: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  IPAddress ip = WiFi.localIP();  Serial.print("IP Address: ");  Serial.println(ip);

  // print the received signal strength:  long rssi = WiFi.RSSI();  Serial.print("signal strength (RSSI):");  Serial.print(rssi);  Serial.println(" dBm");}

WiFi Web ClientThis example shows you how to make a HTTP request using a WiFi shield. It returns a Google search for the term "Arduino". The results of this search are viewable as HTML through your Arduino's serial window.This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board

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

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*  Web client  This sketch connects to a website (http://www.google.com) using a WiFi shield.  This example is written for a network using WPA encryption. For  WEP or WPA, change the Wifi.begin() call accordingly.  This example is written for a network using WPA encryption. For  WEP or WPA, change the Wifi.begin() call accordingly.  Circuit: * WiFi shield attached  created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 by Tom Igoe */

#include <SPI.h>#include <WiFi.h>

char ssid[] = "yourNetwork"; //  your network SSID (name) char pass[] = "secretPassword";    // your network password (use for WPA, or use as key for WEP)

Page 219: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server://IPAddress server(74,125,232,128);   // numeric IP for Google (no DNS)char server[] = "www.google.com";    // name address for Google (using DNS)

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

void setup() {  //Initialize serial and wait for port to open:  Serial.begin(9600);   while (!Serial) {    ; // wait for serial port to connect. Needed for Leonardo only  }    // check for the presence of the shield:  if (WiFi.status() == WL_NO_SHIELD) {    Serial.println("WiFi shield not present");     // don't continue:    while(true);  }     // attempt to connect to Wifi network:  while (status != WL_CONNECTED) {     Serial.print("Attempting to connect to SSID: ");    Serial.println(ssid);    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:        status = WiFi.begin(ssid, pass);      // wait 10 seconds for connection:    delay(10000);  }   Serial.println("Connected to wifi");  printWifiStatus();    Serial.println("\nStarting connection to server...");  // if you get a connection, report back via serial:  if (client.connect(server, 80)) {    Serial.println("connected to server");    // Make a HTTP request:    client.println("GET /search?q=arduino HTTP/1.1");    client.println("Host: www.google.com");    client.println("Connection: close");    client.println();  }}

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

  // if the server's disconnected, stop the client:  if (!client.connected()) {    Serial.println();    Serial.println("disconnecting from server.");    client.stop();

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

void printWifiStatus() {  // print the SSID of the network you're attached to:  Serial.print("SSID: ");  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:  IPAddress ip = WiFi.localIP();  Serial.print("IP Address: ");  Serial.println(ip);

  // print the received signal strength:  long rssi = WiFi.RSSI();  Serial.print("signal strength (RSSI):");  Serial.print(rssi);  Serial.println(" dBm");}WiFi Web Client RepeatingThis example shows you how to make repeated HTTP requests using a WiFi shield. It connects tohttp://www.arduino.cc/latest.txt. The content of the page is viewable through your Arduino's serial window.This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board

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

Page 220: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*  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/WifiWebClientRepeating 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 passwordint keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

// Initialize the Wifi client libraryWiFiClient 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 millisecondsconst unsigned long postingInterval = 10L * 1000L; // 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) {    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:

Page 221: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

    delay(10000);  }  // you're connected now, so print out the status:  printWifiStatus();}

void loop() {  // if there's incoming data from the net connection.  // send it out the serial port.  This is for debugging  // purposes only:  while (client.available()) {    char c = client.read();    Serial.write(c);  }

  // if ten seconds have passed since your last connection,  // then connect again and send data:  if (millis() - lastConnectionTime > postingInterval) {    httpRequest();  }

}

// this method makes a HTTP connection to the server:void httpRequest() {  // close any connection before send a new request.  // This will free the socket on the WiFi shield  client.stop();

  // if there's a successful connection:  if (client.connect(server, 80)) {    Serial.println("connecting...");    // send the HTTP PUT request:    client.println("GET /latest.txt HTTP/1.1");    client.println("Host: www.arduino.cc");    client.println("User-Agent: ArduinoWiFi/1.1");    client.println("Connection: close");    client.println();

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

void printWifiStatus() {  // print the SSID of the network you're attached to:  Serial.print("SSID: ");  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:  IPAddress ip = WiFi.localIP();  Serial.print("IP Address: ");  Serial.println(ip);

  // print the received signal strength:  long rssi = WiFi.RSSI();  Serial.print("signal strength (RSSI):");  Serial.print(rssi);  Serial.println(" dBm");}

WiFi Web ServerIn this example, you will use your WiFi Shield and your Arduino to create a simple Web server. Using the WiFi library, your device will be able to answer a HTTP request with your WiFI shield. After opening a browser and navigating to your WiFishield's IP address, your Arduino will respond with just enough HTML for a browser to display the input values from all six analog pins.This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board (optional) Six analog sensors attached

to Analog in Pins 0-5CircuitThe 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

Page 222: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*  WiFi Web Server  A simple web server that shows the value of the analog input pins. using a WiFi shield.  This example is written for a network using WPA encryption. For  WEP or WPA, change the Wifi.begin() call accordingly.  Circuit: * WiFi shield attached * Analog inputs attached to pins A0 through A5 (optional)  created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 by Tom Igoe

 */

#include <SPI.h>#include <WiFi.h>

char ssid[] = "yourNetwork";      // your network

SSID (name) char pass[] = "secretPassword";   // your network passwordint 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  WiFiClient client = server.available();  if (client) {    Serial.println("new client");    // an http request ends with a blank line    boolean currentLineIsBlank = true;    while (client.connected()) {      if (client.available()) {        char c = client.read();        Serial.write(c);        // if you've gotten to the end of the line (received a newline        // character) and the line is blank, the http request has ended,        // so you can send a reply        if (c == '\n' && currentLineIsBlank) {          // send a standard http response header          client.println("HTTP/1.1 200 OK");          client.println("Content-Type: text/html");

Page 223: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

          client.println("Connection: close");  // the connection will be closed after completion of the response          client.println("Refresh: 5");  // refresh the page automatically every 5 sec          client.println();          client.println("<!DOCTYPE HTML>");          client.println("<html>");          // output the value of each analog input pin        for (int analogChannel = 0; analogChannel < 6; analogChannel++) {          int sensorReading = analogRead(analogChannel);            client.print("analog input ");            client.print(analogChannel);            client.print(" is ");            client.print(sensorReading);            client.println("<br />");                 }          client.println("</html>");           break;        }        if (c == '\n') {          // you're starting a new line          currentLineIsBlank = true;        }         else if (c != '\r') {          // you've gotten a character on the current line          currentLineIsBlank = false;        }      }    }    // give the web browser time to receive the data    delay(1);        // close the connection:    client.stop();    Serial.println("client disonnected");  }}

void printWifiStatus() {  // print the SSID of the network you're attached to:  Serial.print("SSID: ");  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:  IPAddress ip = WiFi.localIP();  Serial.print("IP Address: ");  Serial.println(ip);

  // print the received signal strength:  long rssi = WiFi.RSSI();  Serial.print("signal strength (RSSI):");  Serial.print(rssi);

  Serial.println(" dBm");}

Send and Receive UDP StringThis sketch waits for a UDP packet on a local port. When a valid packet is received, an acknowledge packet is sent back to the client on a specified outgoing port.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board

CircuitThe WiFi shield uses pins 10, 11, 12, and 13 for the SPI connection to the HDG104 module. Digital pin 4 is used to control the slave select pin on the SD card.You should have access to a 802.11b/g wireless network that connects to the internet for this example. You will need to change the network settings in the sketch to correspond to your particular networks SSID.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*  WiFi UDP Send and Receive String

 This sketch wait an UDP packet on localPort using a WiFi shield. When a packet is received an Acknowledge

Page 224: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

packet is sent to the client on port remotePort

 Circuit: * WiFi shield attached

 created 30 December 2012 by dlf (Metodo2 srl)

 */

#include <SPI.h>#include <WiFi.h>#include <WiFiUdp.h>

int status = WL_IDLE_STATUS;char ssid[] = "yourNetwork"; //  your network SSID (name)char pass[] = "secretPassword";    // your network password (use for WPA, or use as key for WEP)int keyIndex = 0;            // your network key Index number (needed only for WEP)

unsigned int localPort = 2390;      // local port to listen on

char packetBuffer[255]; //buffer to hold incoming packetchar  ReplyBuffer[] = "acknowledged";       // a string to send back

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  }

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

    // wait 10 seconds for connection:

    delay(10000);  }  Serial.println("Connected to wifi");  printWifiStatus();

  Serial.println("\nStarting connection to server...");  // if you get a connection, report back via serial:  Udp.begin(localPort);}

void loop() {

  // if there's data available, read a packet  int packetSize = Udp.parsePacket();  if (packetSize)  {    Serial.print("Received packet of size ");    Serial.println(packetSize);    Serial.print("From ");    IPAddress remoteIp = Udp.remoteIP();    Serial.print(remoteIp);    Serial.print(", port ");    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer    int len = Udp.read(packetBuffer, 255);    if (len > 0) packetBuffer[len] = 0;    Serial.println("Contents:");    Serial.println(packetBuffer);

    // send a reply, to the IP address and port that sent us the packet we received    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());    Udp.write(ReplyBuffer);    Udp.endPacket();  }}

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

Network Time Protocol (NTP) Client

Page 225: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

In this example, you will use your WiFi Shield and your Arduino to query a Network Time Protocol (NTP) server. This way, your Arduino can get the time from the Internet.Hardware Required

Arduino WiFi Shield Shield-compatible Arduino board

CircuitThe WiFi shield uses pins 10, 11, 12, and 13 for the SPI connection to the HDG104 module. Digital pin 4 is used to control the slave select pin on the SD card.You should have access to a 802.11b/g wireless network that connects to the internet for this example. You will need to change the network settings in the sketch to correspond to your particular networks SSID.

image developed using Fritzing. For more circuit examples, see the Fritzing project pageIn the above image, the Arduino would be stacked below the WiFi shield.Code:/*

 Udp NTP Client

 Get the time from a Network Time Protocol (NTP) time server Demonstrates use of UDP sendPacket and ReceivePacket For more on NTP time servers and the messages needed to communicate with them, see

http://en.wikipedia.org/wiki/Network_Time_Protocol

 created 4 Sep 2010 by Michael Margolis modified 9 Apr 2012 by Tom Igoe

 This code is in the public domain.

 */

#include <SPI.h>#include <WiFi.h>#include <WiFiUdp.h>

int status = WL_IDLE_STATUS;char ssid[] = "mynetwork";  //  your network SSID (name)char pass[] = "mypassword";       // your network passwordint keyIndex = 0;            // your network key Index number (needed only for WEP)

unsigned int localPort = 2390;      // local port to listen for UDP packets

IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDPWiFiUDP Udp;

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

  // 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:

Page 226: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  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 = 2208988800UL;

    // 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 addressunsigned long sendNTPpacket(IPAddress& address){  //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");

Page 227: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

  // 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 LibraryThis 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 I2C / TWI pinsUno, Ethernet A4 (SDA), A5 (SCL)

Mega2560 20 (SDA), 21 (SCL)Leonardo 2 (SDA), 3 (SCL)

Due 20 (SDA), 21 (SCL), SDA1, SCL1

As of Arduino 1.0, the library inherits from the Stream functions, making it consistent with other read/write libraries. Because of this, send() and receive() have been replaced with read() and write().NoteThere are both 7- and 8-bit versions of I2C addresses. 7 bits identify the

device, and the eighth bit determines if it's being written to or read from. The Wire library uses 7 bit addresses throughout. If you have a datasheet or sample code that uses 8 bit address, you'll want to drop the low bit (i.e. shift the value one bit to the right), yielding an address between 0 and 127.

Functions begin () requestFrom () beginTransmission () endTransmission () write () available () read () onReceive () onRequest ()

Wire.begin()Wire.begin(address)DescriptionInitiate the Wire library and join the I2C bus as a master or slave. This should normally be called only once.Parametersaddress: the 7-bit slave address (optional); if not specified, join the bus as a master.ReturnsNone

Wire.requestFrom()DescriptionUsed 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

Page 228: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

master device to send multiple requests while in control.The default value is true.SyntaxWire.requestFrom(address, quantity)Wire.requestFrom(address, quantity, stop)Parametersaddress: the 7-bit address of the device to request bytes fromquantity: the number of bytes to requeststop : 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.Returnsbyte : the number of bytes returned from the slave device

Wire.beginTransmission(address)DescriptionBegin 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().Parametersaddress: the 7-bit address of the device to transmit toReturnsNone

Wire.endTransmission()DescriptionEnds 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.SyntaxWire.endTransmission()Wire.endTransmission(stop)Parametersstop : boolean. true will send a stop message, releasing the bus after transmission. false will send a restart, keeping the connection active.Returnsbyte, 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()DescriptionWrites 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()).SyntaxWire.write(value) Wire.write(string) Wire.write(data, length)Parametersvalue: a value to send as a single bytestring: a string to send as a series of bytesdata: an array of data to send as byteslength: the number of bytes to transmitReturnsbyte: write() will return the number of bytes written, though reading that number is optional

Page 229: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long

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()DescriptionReturns 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.ParametersNoneReturnsThe number of bytes available for reading.

read()DescriptionReads 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.SyntaxWire.read() Parametersnone

ReturnsThe next byte receivedExample#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);    // request 6 bytes from slave device #2

  while(Wire.available())    // slave may send less than requested  {     char c = Wire.read();    // receive a byte as character    Serial.print(c);         // print the character  }

  delay(500);}

Wire.onReceive(handler)DescriptionRegisters a function to be called when a slave device receives a transmission from a master.Parametershandler: 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 numBytes)ReturnsNone

Wire.onRequest(handler)DescriptionRegister a function to be called when a master requests data from this slave device.Parametershandler: the function to be called, takes no parameters and returns nothing, e.g.: void myHandler()ReturnsNone

Page 230: api.ning.comapi.ning.com/.../BibliotecaArduino.docx  · Web viewMotors and PWM: TLC5940 - 16 ... unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long