arduino libraries

229
Libraries The Arduino environment can be extended through the use of libraries, just like most programming platforms. Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data. A number of libraries come installed with the IDE, but you can also download or create your own. See these instructions for details on installing libraries. There's also a tutorial on writing your own libraries. See the API Style Guide for information on making a good Arduino-style API for your library. To use a library in a sketch, select it from Sketch > Import Library. Standard Libraries EEPROM - reading and writing to "permanent" storage Ethernet - for connecting to the internet using the Arduino Ethernet Shield Firmata - for communicating with applications on the computer using a standard serial protocol. GSM - for connecting to a GSM/GRPS network with the GSM shield. LiquidCrystal - for controlling liquid crystal displays (LCDs) SD - for reading and writing SD cards Servo - for controlling servo motors SPI - for communicating with devices using the Serial Peripheral Interface (SPI) Bus SoftwareSerial - for serial communication on any digital pins. Version 1.0 and later of Arduino incorporate Mikal Hart'sNewSoftSerial library as SoftwareSerial. Stepper - for controlling stepper motors TFT - for drawing text , images, and shapes on the Arduino TFT screen WiFi - for connecting to the internet using the Arduino WiFi shield Wire - Two Wire Interface (TWI/I2C) for sending and receiving data over a net of devices or sensors. The Matrix and Sprite libraries are no longer part of the core distribution. Due Only Libraries Audio - Play audio files from a SD card. Scheduler - Manage multiple 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 Robot Arduino 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 Libraries If you're using one of these libraries, you need to install it first. See these instructions for details on installation. There's also a tutorial on writing your own libraries. Communication (networking and protocols): Messenger - for processing text-based messages from the computer NewSoftSerial - an improved version of the SoftwareSerial library OneWire - control devices (from Dallas Semiconductor) that use the One Wire protocol. PS2Keyboard - read characters from a PS2 keyboard. Simple Message System - send messages between Arduino and the computer SSerial2Mobile - send text messages or emails using a cell phone (via AT commands over software serial)

Upload: danie-fsm

Post on 07-Sep-2015

328 views

Category:

Documents


32 download

DESCRIPTION

Provides libraries that will facilitate programming numerous applications.

TRANSCRIPT

  • 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

    Robot - this library enables easy access to the functions of the Arduino Robot Arduino Yn Bridge Library

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

    Keyboard - Send keystrokes to an attached computer.

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

    Messenger - for processing text-based messages from the computer

    NewSoftSerial - an improved version of the SoftwareSerial library

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

    PS2Keyboard - read characters from a PS2 keyboard.

    Simple Message System - send messages between Arduino and the computer

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

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

    X10 - Sending X10 signals over AC power lines

    XBee - for communicating with XBees in API mode

    SerialControl - Remote control other Arduinos over a serial connection Sensing:

    Capacitive Sensing - turn two or more pins into capacitive sensors

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

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

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

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

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

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

    LedDisplay - control of a 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 pin Motors and PWM:

    TLC5940 - 16 channel 12 bit PWM controller. Timing:

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

    Metro - help you time actions at regular intervals

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

    PString - a lightweight class for printing to buffers

    Streaming - a method to simplify print statements

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

    read() write()

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

  • { Serial.begin(9600); } void loop() { value = EEPROM.read(a); Serial.print(a); Serial.print("\t"); Serial.print(value); Serial.println(); a = a + 1; if (a == 512) a = 0; delay(500); }

    write() Description Write a byte to the EEPROM. Syntax EEPROM.write(address, value) Parameters address: the location to write to, starting from 0 (int) value: the value to write, from 0 to 255 (byte) Returns none Note An EEPROM write takes 3.3 ms to complete. The EEPROM memory has a specified life of 100,000 write/erase cycles, so you may need to be careful about how often you write to it. Example #include void setup() { for (int i = 0; i < 255; i++) EEPROM.write(i, i); } void loop() { } Ethernet library With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet. It can serve as either a server accepting incoming connections or a client

    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.

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

  • begin() localIP() maintain()

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

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

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

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

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

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

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

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

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

  • Ethernet.localIP() Description Obtains the IP address of the Ethernet shield. Useful when the address is auto assigned through DHCP. Syntax Ethernet.localIP(); Parameters none Returns the IP address Example #include #include // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): EthernetClient client; void setup() { // start the serial library: Serial.begin(9600); // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: for(;;) ; } // print your local IP address: Serial.println(Ethernet.localIP()); } void loop() { } Ethernet.maintain() Description Allows for the renewal of DHCP leases. When assigned an IP address via DHCP, ethernet devices are given a lease on the address for an amount of time. With Ethernet.maintain(), it is

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

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

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

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

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

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

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

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

    available() Description Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling client.stop(). available() inherits from the Stream utility class. Syntax server.available() Parameters None Returns a Client object; if no Client has data available for reading, this object will evaluate to false in an if-statement (see the example below) Example #include #include // the media access control (ethernet hardware) address for the shield: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //the IP address for the shield: byte ip[] = { 10, 0, 0, 177 }; // the router's gateway address: byte gateway[] = { 10, 0, 0, 1 }; // the subnet: byte subnet[] = { 255, 255, 0, 0 }; // telnet defaults to port 23 EthernetServer server = EthernetServer(23); void setup() { // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet); // start listening for clients server.begin(); } void loop() { // if an incoming client connects, there will be bytes available to read: EthernetClient client = server.available();

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

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

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

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

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

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

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

    EthernetClient() Description Creates a client which can connect to a specified internet IP address and port (defined in the client.connect() function). Syntax EthernetClient() Parameters None Example #include #include 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(;;) ; } } Ethernet : if (EthernetClient) Description Indicates if the specified Ethernet client is ready. Syntax if (client) Parameters none Returns boolean : returns true if the specified client is available. Example: #include #include 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() Description Whether or not the client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data. Syntax client.connected() Parameters none Returns Returns true if the client is connected, false if not. Example #include #include byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte ip[] = { 10, 0, 0, 177 }; byte server[] = { 64, 233, 187, 99 }; // Google EthernetClient client; void setup() { Ethernet.begin(mac, ip); Serial.begin(9600); client.connect(server, 80); delay(1000); Serial.println("connecting..."); if (client.connected()) {

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

    connect() Description Connects to a specified IP address and port. The return value indicates success or failure. Also supports DNS lookups when using a domain name. Syntax client.connect() client.connect(ip, port) client.connect(URL, port) Parameters ip: the IP address that the client will connect to (array of 4 bytes) URL: the domain name the client will connect to (string, ex.:"arduino.cc") port: the port that the client will connect to (int) Returns Returns true if the connection succeeds, false if not. Example #include #include 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() Description Write data to the server the client is connected to. This data is sent as a byte or series of bytes. Syntax client.write(val) client.write(buf, len) Parameters val: a value to send as a single byte (byte or char) buf: an array to send as a series of bytes (byte or char) len: the length of the buffer Returns byte write() returns the number of bytes written. It is not necessary to read this value.

    print()

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

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

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

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

    read()

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

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

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

    #include #include // 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()

  • Description Reads UDP data from the specified buffer. If no arguments are given, it will return the next character in the buffer. This function can only be successfully called after UDP.parsePacket(). Syntax UDP.read(); UDP.read(packetBuffer, MaxSize); Parameters packetBuffer: buffer to hold incoming packets (char) MaxSize: maximum size of the buffer (int) Returns char : returns the characters in the buffer Example #include #include #include // 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; 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() Description Writes UDP data to the remote connection. Must be wrapped between beginPacket() and endPacket(). beginPacket() initializes the packet of data, it is not sent until endPacket() is called. Syntax UDP.write(message); UDP.write(buffer, size); Parameters message: the outgoing message (char) buffer: an array to send as a series of bytes (byte or char) size: the length of the buffer Returns byte : returns the number of characters sent. This does not have to be read Example #include #include #include // 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() { Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write("hello"); Udp.endPacket(); } Ethernet : UDP.beginPacket() Description Starts a connection to write UDP data to the remote connection Syntax UDP.beginPacket(remoteIP, remotePort); Parameters remoteIP: the IP address of the remote connection (4 bytes) remotePort: the port of the remote connection (int)

    Returns None Example #include #include #include // 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() { Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write("hello"); Udp.endPacket(); } Ethernet : UDP.endPacket() Description Called after writing UDP data to the remote connection. Syntax UDP.endPacket(); Parameters None Returns None Example #include #include #include // 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() { Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write("hello"); Udp.endPacket(); } Ethernet : UDP.parsePacket() Description Checks for the presence of a UDP packet, and reports the size. parsePacket() must be called before reading the buffer with UDP.read(). Syntax UDP.parsePacket(); Parameters None Returns int: the size of a received UDP packet Example #include // needed for Arduino versions later than 0018 #include #include // 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 UDP EthernetUDP 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() Description Get the number of bytes (characters) available for reading from the buffer. This is data that's already arrived. This function can only be successfully called after UDP.parsePacket(). available() inherits from the Stream utility class. Syntax UDP.available() Parameters None Returns the number of bytes available to read Example #include #include #include // 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;

  • 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(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() Description Disconnect from the server. Release any resource being used during the UDP session. Syntax EthernetUDP.stop() Parameters none Returns none Ethernet : UDP.remoteIP() Description Gets the IP address of the remote connection. This function must be called after UDP.parsePacket().

    Syntax UDP.remoteIP(); Parameters None Returns 4 bytes : the IP address of the remote connection Example #include #include #include // 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() { 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() Description Gets the port of the remote UDP connection.

  • This function must be called after UDP.parsePacket(). Syntax UDP.remotePort(); Parameters None Returns int : the port of the UDP connection to a remote host Example #include #include #include // 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; 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); } } Chat Server A simple server that distributes any incoming messages to all connected clients. To use, open a terminal window, telnet to your devices IP address, and type away. Any incoming text will be sent to all connected clients (including the one typing). Additionally, you will be able to see the client's input in your serial monitor as well. Hardware Required

    Arduino Ethernet Shield Shield-compatible Arduino board

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

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

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

  • device's IP address and type. You can see the client's input in the serial monitor as well. Using an Arduino Wiznet Ethernet shield. 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 #include // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network. // gateway and subnet are optional: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192,168,1, 177); IPAddress gateway(192,168,1, 1); IPAddress subnet(255, 255, 0, 0); // telnet defaults to port 23 EthernetServer server(23); boolean alreadyConnected = false; // whether or not the client was connected previously void setup() { // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet); // start listening for clients server.begin(); // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } Serial.print("Chat server address:"); Serial.println(Ethernet.localIP()); }

    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 Client This example shows you how to make a HTTP request using an Ethernet shield. It returns a Google search for the term "Arduino". The results of this search are viewable as HTML through your Arduino's serial window. Hardware Required

    Arduino Ethernet Shield Shield-compatible Arduino board

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

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

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

  • Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 created 18 Dec 2009 by David A. Mellis modified 9 Apr 2012 by Tom Igoe, based on work by Adrian McEwen */ #include #include // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: //IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) char server[] = "www.google.com"; // name address for Google (using DNS) // Set the static IP address to use if the DHCP fails to assign IPAddress ip(192,168,0,177); // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): EthernetClient client; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore:

    // try to congifure using IP address instead of DHCP: Ethernet.begin(mac, ip); } // give the Ethernet shield a second to initialize: delay(1000); Serial.println("connecting..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("connected"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.1"); client.println("Host: www.google.com"); client.println("Connection: close"); client.println(); } else { // kf you didn't get a connection to the server: Serial.println("connection failed"); } } void loop() { // if there are incoming bytes available // from the server, read them and print them: if (client.available()) { char c = client.read(); Serial.print(c); } // if the server's disconnected, stop the client: if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); // do nothing forevermore: while(true); } } Web Client Repeating This example shows you how to make repeated HTTP requests using an Ethernet shield. This example uses DNS, by assigning the Ethernet client with a MAC address, IP address, and DNS address. It connects

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

    Arduino Ethernet Shield Shield-compatible Arduino board

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

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

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

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

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

  • ethernet"); client.println("Connection: close"); client.println(); // note the time that the connection was made: lastConnectionTime = millis(); } else { // if you couldn't make a connection: Serial.println("connection failed"); Serial.println("disconnecting."); client.stop(); } } Web Server In this example, you will use your Ethernet Shield and your Arduino to create a simple Web server. Using the Ethernet library, your device will be able to answer a HTTP request with your Ethernet shield. After opening a browser and navigating to your Ethernet shield's IP address, your Arduino will respond with just enough HTML for a browser to display the input values from all six analog pins. Hardware Required

    Arduino Ethernet Shield Shield-compatible Arduino board

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

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

  • Code /* Web Server A simple web server that shows the value of the analog input pins. 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 #include // 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(""); client.println(""); // 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(""); } client.println(""); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disconnected");

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

    Arduino Ethernet Shield or Arduino Ethernet

    Shield-compatible Arduino board One analog sensor to attached to the

    Ethernet Shield Software Required

    xively.com account pachube.com feed that accepts two

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

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

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

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

    address for xively API unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds boolean lastConnected = false; // state of the connection last time through the main loop const unsigned long postingInterval = 10*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();

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

    Arduino Ethernet Shield or Arduino Ethernet board

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

    Ethernet Shield Software Required

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

    item Circuit The Ethernet shield allows you to connect a WizNet Ethernet controller to

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

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

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

    // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: IPAddress server(216,52,233,121); // numeric IP for api.xively.com //char server[] = "api.xively.com"; // name address for xively API unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds boolean lastConnected = false; // state of the connection last time through the main loop const unsigned long postingInterval = 10*1000; //delay between updates to xively.com void setup() { // 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();

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

    SCP1000 Pressure Sensor Breakout Board

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

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

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

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

    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
  • 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
  • Code /* UDPSendReceive.pde: This sketch receives UDP message strings, prints them to the serial port and sends an "acknowledge" string back to the sender

    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 // needed for Arduino versions later than 0018 #include #include // 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 data char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, char ReplyBuffer[] = "acknowledged"; // a string to send back // An EthernetUDP instance to let us send and receive packets over UDP EthernetUDP Udp; void setup() { // start the Ethernet and UDP: Ethernet.begin(mac,ip); Udp.begin(localPort); Serial.begin(9600); } 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 ); //
  • The shield should be connected to a network with an ethernet cable. You will need to change the network settings in the program to correspond to your network.

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

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

  • Demonstrates use of UDP sendPacket and ReceivePacket For more on NTP time servers and the messages needed to communicate with them, see http://en.wikipedia.org/wiki/Network_Time_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 #include #include // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; unsigned int localPort = 8888; // 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

    packets over UDP EthernetUDP Udp; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // 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

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

    Arduino Ethernet Shield Shield-compatible Arduino board

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

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

    image developed using Fritzing. For more circuit examples, see the Fritzing project page In the above image, your Arduino would be stacked below the Ethernet shield. Code /* DNS and DHCP-based Web client This sketch connects to a website (http://www.google.com) using an Arduino Wiznet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 created 18 Dec 2009 by David A. Mellis modified 9 Apr 2012 by Tom Igoe, based on work by Adrian McEwen */ #include #include // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield

    byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; 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 Server This example connects to a Telnet server using an Ethernet shield. Messages from the server are printed out via the serial port. Messages can be sent to the remote server serially as well. The Serial monitor works well for this purpose. This version attempts to get an IP address using DHCP. An IP address can be assigned via DHCP when Ethernet.begin(mac) is called. Be careful, when using the DHCP extensions, sketch size increases significantly. Hardware Required

    Arduino Ethernet Shield Shield-compatible Arduino board

    Software Required A telnet server Alternatively, Processing has

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

    the program to correspond to your network.

    image developed using Fritzing. For more circuit examples, see the Fritzing project page In the above image, your Arduino would be stacked below the Ethernet shield. 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 #include // 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 23 EthernetServer 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 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 Printer This sketch uses the DHCP extensions to the Ethernet library to get an IP address via DHCP and print the address obtained using an Arduino Ethernet shield. DHCP is used to assign an IP address when Ethernet.begin(mac) is called. Using DHCP significantly increases the size of a sketch. Using the localIP() function, the assigned IP address is sent out via the serial monitor. Hardware Required

    Arduino Ethernet Shield Shield-compatible Arduino board

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

  • image developed using Fritzing. For more circuit examples, see the Fritzing project page In the above image, your Arduino would be stacked below the Ethernet shield. Code /* DHCP-based IP printer This sketch uses the DHCP extensions to the Ethernet library to get an IP address via DHCP and print the address obtained. using an Arduino Wiznet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 created 12 April 2011 modified 9 Apr 2012 by Tom Igoe */ #include #include // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is

    default for HTTP): EthernetClient client; void setup() { // 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 Client This example connects to a Telnet server using an Ethernet shield. Messages from the server are printed out via the serial port. Messages can be sent to the remote server serially as well. The Serial monitor works well for this purpose. Hardware Required

    Arduino Ethernet Shield Shield-compatible Arduino board

    Software Required A telnet server

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

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

    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 #in