Ethernet Shield V2.4

From Wiki 来自痴汉的爱
Jump to: navigation, search

Contents

Overview

The Seeeduino V2.4 Ethernet shield can be used to provide your projects with internet connectivity. The shield features the W5200 Ethernet controller to support up to eight simulatneous TCP/UDP connections. The shield also has a microSD card slot to support projects which require storing large amounts of data for Internet of Things (IoT) applications. The RJ45 port (Where the Ethernet cable is connected to) is low enough to allow you to stack more shields on top of this one if needed.

Product Page: W5200 Ethernet Shield V2.4

Specification

  • High speed Ethernet controller - W5200
  • SPI interface
  • 32 Kbytes inner buffer
  • Minimal RJ45 Ethernet port
  • Supports up to eight simultaneous TCP/UDP connections
  • microSD card socket for data intensive projects
  • Grove ports for I2C and UART

Shield Interface and Components

Overview

See the text below the image for a description of the components highlighted in the Ethernet shield.

Ethernet shield interface/components top side


  1. Ethernet port RJ45: This is where you connect the Ethernet cable to the shield.
  2. PWR(Power) LED: is lit up green when the shield is receiving power from a source.
  3. SW1: Reset switch, resets the W5200 Ethernet controller and Arduino/Seeeduino board.
  4. W5200 Ethernet controller: This chip is what makes the TCP/IP communication possible. The SPI pins MOSI, MISO, SCK, and CS/SS of this chip are connected to digital pins 11, 12, 13, and 10 respectively.
  5. I2C and UART grove connectors: The UART connector is connected to digital pin 0 and 1 for RX and TX respectively. The I2C connector is connected to Analog pins 5 and 4 (bottom right of the siheld) for SCL and SDA as well as the pins SCL and SDA (top left of the shield).
  6. microSD card socket: A microSD card socket for projects that require memory storage. The SPI pins MOSI, MISO, SCK, and CS/SS of this socket are connected to digital pins 11, 12, 13, and 4 respectively.
  7. ICSP Connector:

Pins Used / Shield Compatibility

SPI Pins:

The Ethernet shield uses digital pins 11, 12, 13, 10, and 4 for SPI communication with the W5200 Ethernet controller and SD card. Therefore, the shield is compatible with any other shield that does not use pins 10, and 4 in this regard.

I2C and UART Pins:

The shield does not make use of this pins but provides easy access to them via the Grove connectors and pins described the Overview section above.

Power Pins:

The shield is powered from the Vin, and 5V pins of the Arduino.

Reset Pin:

The RST pin is used by the SW1 switch, pressing this switch will reset both the W5200 Ethernet controller and Arduino board.

Seeeduino Ethernet Library

The library for this Ethernet shield's is the same as the Arduino's Ethernet library with the difference that we have replaced the W5100.h/cpp and socket.h/cpp files and references with versions that work with the newer W5200 controller which is what our shield has.

Setup

  1. Goto github and download the W5200 Ethernet Shield's library.
  2. Unzip the downloaded file and paste the folder into your …/arduino/libraries/ folder.
  3. Start the Arduino IDE (or restart if it is open).

Usage

In addition to the various examples/applications we provide in this WiKi you may check out the Arduino's "Ethernet library" reference page for a detail description of the classes and functions the library offers.

SD Card Library

As described in the "Overview" section of this WiKi, the Seeeduino Ethernet shield incorporates a microSD card port for storage/data intensive projects. The shield uses the SPI port to communicate with the microSD and is therefore compatible with the Arduino's SD card library on pin 4 for chip select (CS).

Setup

The SD card library is already installed with the Arduino IDE in the arduino/libraries folder.

Ethernet Shield Examples/Applications

Example 1: How To Connect To an Internet Access Point / Router

Let The Access Point Automatically Assign an IP Address

The code below is the basic code needed to connect to an internet router or access point. The access point will automatically assign an IP address to Ethernet shield upon connection.

#include <SPI.h>
#include <EthernetV2_0.h>
 
// Enter a MAC address for your controller below.
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
 
// CS pin of W5200 Controller
#define W5200_CS  10
// CS pin of SD card
#define SDCARD_CS 4
 
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // The SD card and ethernet controller use the same SPI port.
  // We need to make sure that the SD card is deselected by setting the SD card CS pin to HIGH
  pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
  // loop until we get a connection
  while(Ethernet.begin(mac)==0){
    Serial.println("DHCP configuration failed");
  }
  // connected to router.
  Serial.println("DHCP configuration succeeded");
  Serial.println(Ethernet.localIP()); // Display the Ethernet shield's local IP address
}
 
 
void loop() {
 
}

Use The IP Address You Want

Instead of letting the access point automatically assign a local IP address to your shield we can define the IP address:

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


and pass this value to the "begin" function:

Ethernet.begin(mac, ip);

There are some caveats to assigning your own defined IP address however:

  • The IP address you select is required to be within the range of the IP address values your internet router or access point allows. You can find this range in your access point's local network webpage, in some routers this will be under "DHCP Server Settings"'s "Start IP Address" and "End IP Address".
  • This version of the "begin" function returns a void value, so you cannot check if the DHCP connection was successful.

How To Find Your Router's Page

  1. In Windows 7, click the start button and search for "Network".
  2. Click on "Network" to open the "Network Page"
  3. Your internet router should be listed under "Networ Infrastructure"
  4. Right click in your router then select "View device webpage"
  5. Your web browser should open and present you with the router's settings webpage.

Example 2: Shield as Web Server

In this example we will show you how to use the Ethernet shield to serve a webpage to a web browser or any other device that requests it.

In the Arduino code we will create a server on port 80 (commonly used for HTTP), and when you visit the shield's IP address on a web browser/client (e.g. Google Chrome, Firefox, Internet Explorer, Safari) the shield will respond back to the browser with a webpage.

HTTP Headers

Let's talk a little bit about what happens in the background communication between the web browser and the Ethernet shield.

When you visit any website or IP address from a web browser the browser sends an HTTP Request to the server (in this case the Ethernet shield). The HTTP Request can vary by browser but a typical request looks like this:

GET / HTTP/1.1\r\n
Host: mywebserver.com\r\n
Connection: keep-alive\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n
User-Agent: Chrome/40.0.2214.93 Safari/537.36\r\n
\r\n

Note: Notice that each of the request's line ends with the two characters "\r\n", commonly known as carriage return (CR) and line feed (LN) respectively. We can use this to our advantage, in the Arduino code we will look for this pattern to know when the browser is done sending this information.

The server (Ethernet shield) will then need to send back an HTTP reply that may look like the following:

HTTP/1.1 200 OK\r\n
Content-Type: text/html\r\n
Connnection: close\r\n
\r\n
<html>
<body>
<h1>Hello World!</h1>
</body>
</html>

This is the HTTP reply we'll send back from the Arduino to the web browser. You now know a little about HTTP request and are ready to get started serving webpages from your shield!


Arduino Code:

Stack the Ethernet shield on the Arduino and upload the code below to it.

#include <SPI.h>
#include <EthernetV2_0.h>
 
// define the controller's MAC address
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
 
// set the server at port 80 for HTTP
EthernetServer server(80);
// Ethernet controller SPI CS pin
#define W5200_CS  10
// SD card SPI CS pin
#define SDCARD_CS 4
 
void setup() {
  Serial.begin(9600);
  // make sure that the SD card is not selected for the SPI port
  // by setting the CS pin to HIGH
  pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);
  // loop until we get a connection to the access point
  while(Ethernet.begin(mac)==0){
    Serial.println("DHCP configuration failed. Trying again...");
  }
  // now that we have a good ethernet connection we can start the server
  server.begin();
  Serial.print("The server can be accessed 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 "\r\n\r\n" so we need to look for that
    // by using several if statements. This is how 
    // we know that we are ready to send the webpage back to the device requesting.
 
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
 
        if (c == '\n' && currentLineIsBlank) {
          // 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.
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connnection: close");
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          client.println("<body>");
          client.println("<h1>My Ethernet Shield Web Page</h1>");
          client.println("<a href=\"http://yahoo.com/\">Link to Yahoo!</a>");
          client.println("<button>Button 1</button>");
          client.println("</body>");
          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 http connection:
    client.stop();
    Serial.println("client disonnected");
  }
}

Open the Arduino's serial comm window and visit the IP address in a web browser. The webpage displayed will be similar to the following:

Arduino webserver webpage as seen in Google Chrome when the ethernet shield's IP address is visited.

The output in the Arduino's serial comm window should be similar to the following:

Arduino serial comm window output when it receives a new browser connection.

Example 3: Control The Arduino's Digital Pins From a Webpage Served by The Shield

The Ethernet shield can be used not only to serve webpages but also receive information from them. In this example we will create a webpage with some buttons that will be used to toggle the Arduino's digital pins, we will connect some LEDs so you can see the toggling in action.

Hardware/Circuit

Connect three LEDs with current limiting resistors as shown in the schematic below:

Three LEDs connected to pins 2,3, 5, and GND.

Arduino Code:

The flow of the code is as follows:

  • When the user "visits" the IP address in a web browser display a webpage with buttons
  • Each button has an ID attribute whose value is the Arduino pin it will control.
  • When a button is pressed send the pin value in a GET request in a parameter called "pin" to the shield.
  • On the Arduino side, read the pin value and toggle the pin.

The webpage makes use of HTML, Javascript, and JQuery ( a Javascript library). If you would like to more about these two languages (HTML and Javascript) and the JQuery library visit http://www.w3schools.com/

Stack the Ethernet shield on your Arduino and upload the code below to it.

#include <SPI.h>
#include <EthernetV2_0.h>
 
int pins[] = {2,3,5}; // the digital pins you want to control. 
// NOTE: do not attempt to control the pins used by the SPI bus or 0,1, and 4 pins
 
// define the controller's MAC address
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
 
// set the server at port 80 for HTTP
int port = 80;
String ipAddress = "";
EthernetServer server(port);
// Ethernet controller SPI CS pin
#define W5200_CS  10
// SD card SPI CS pin
#define SDCARD_CS 4
 
void setup() {
  // the pins to be OUTPUTS and be LOW intially
  for(int i=0; i<sizeof(pins)/sizeof(pins[0]);i++)
  {
    pinMode(pins[i],OUTPUT);
    digitalWrite(pins[i],LOW);
  }
 
  Serial.begin(9600);
  // make sure that the SD card is not selected for the SPI port
  // by setting the CS pin to HIGH
  pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);
  // loop until we get a connection to the access point
  while(Ethernet.begin(mac)==0){
    Serial.println("DHCP configuration failed. Trying again...");
  }
  // now that we have a good ethernet connection we can start the server
  server.begin();
  Serial.print("The server can be accessed at: ");
  IPAddress ip = Ethernet.localIP();
  ipAddress += ip[0];
  ipAddress+= ".";
  ipAddress += ip[1];
  ipAddress += ".";
  ipAddress += ip[2];
  ipAddress += ".";
  ipAddress += ip[3];
  Serial.println(ipAddress);
}
 
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);
 
        // look for the string "pin=" in the browser/client request
        if (!client.find("pin=")) { 
          // the string "pin=" is not present in the browser/client HTTP request
          // so display the buttons webpage.
 
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connnection: close");
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.print("<html>");
          client.print("<head>");
          client.print("<title>WiFi Shield Webpage</title>");
          client.print("</head>");
          client.print("<body>");
          client.print("<h1>LED Toggle Webpage</h1>");
 
          // Create the HTML button code e.g. <button id="xx" class="led">Toggle Pin xx</button> where xx is the pin number
  	  // In the <button id="xx" class="led"> tags, the ID attribute is the value sent to the arduino via the "pin" GET parameter
           for(int i=0; i<sizeof(pins)/sizeof(pins[0]);i++)
           {
              String buttonHTML = "<button id=\"";
              buttonHTML+=pins[i];
              buttonHTML+="\" class=\"led\">Toggle Pin ";
              buttonHTML+=pins[i];
              buttonHTML+="</button><br />";
              client.println(buttonHTML);
           }
 
          client.print("<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>"); // include the JQuery library hosted by Google
          client.print("<script type=\"text/javascript\">"); // beg javascript code
          client.print("$(document).ready(function(){");
          client.print("$(\".led\").click(function(){");
          client.print("var p = $(this).attr('id');"); // get id value (i.e. pin13, pin12, or pin11)
 
          // create the JQuery $.get function "$.get(\"http://ipaddress:port/\", {pin:p},function(data){alert(data)});"
          // The .get functions sends and HTTP GET request to the IP address of the shield with the parameter "pin" and value "p", then executes the function alert
          String get = "$.get(\"http://";
          get+=ipAddress;
          get+=":";
          get+=port;
          get+="/\", {pin:p},function(data){alert(data)});";
          client.print(get);
          client.print("});"); // close the click function
          client.print("});"); // close the read function
          client.print("</script>"); // end the javascript snippet
          client.print("</body>"); // end HTML body
          client.print("</html>"); // end HTML 
          break;
        }else{
          // The string "pin=" is found in the browser/client rquest, this meanst that the user wants to toggle the LEDs
          int pinNumber = (client.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
          int secondNumber = (client.read()-48);
          if(secondNumber>=0 && secondNumber<=9)
          {
          pinNumber*=10;
          pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
          }
 
          digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin 
 
          // Build pinstate string. The Arduino replies to the browser with this string.
          String pinState = "Pin ";
          pinState+=pinNumber;
          pinState+=" is ";
          if(digitalRead(pinNumber)) // check if the pin is ON or OFF
          {
          pinState+="ON"; // the pin is on
          }
          else
          {
           pinState+="OFF";  // the pin is off
          }
 
          // Send HTTP response back to browser/client
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connnection: close");
          client.println();
          client.println(pinState);
          break; 
        }
 
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }
}

Open the serial monitor window and wait for the shield to respond with it's assigned IP address. Now open your web browser and visit that IP address, a website like the one below should display:

Pin/LED control webpage served from the Ethernet shield as seen in Google Chrome.

Now press one of the buttons. The Arduino will toggle the LED/pin and reply back with the pin's ON/OFF state in an alert dialog as shown below:

The Arduino's reply to Google Chrome displayed in an alert dialog.

The Arduino's serial monitor output should look like this:

Arduino Ethernet shield's serial communication's output.

Example 4: Request Weather Information From Any City in The World (Shield as Web Client)

A web client can be used to send and receive information from a web server, the Ethernet shield can be used as a client and we'll show you how in this example. We'll use an application programming interface (API) provided by OpenWeatherMap to request weather data from any city in the world. The way the OpenWeatherMap API works is you send the city name and country to their webserver and they reply back with weather data for that city.

The HTTP Request

For this example we'll be requesting weather information for San Francisco, U.S. The HTTP request we have to send from the Arduino through the internet shield will have to look like this:

GET /data/2.5/weather?q=San%20Francisco,ca HTTP/1.1\r\n
Host: api.openweathermap.org\r\n
\r\n

Note: The characters "%20" are the URL encoded representation of the space " " character.

You can actually see the result our Ethernet shield will receive from api.openweathermap.org when it sends the HTTP request above by visiting this URL http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco,ca

When you visit the URL you should see a JSON string similar to the following:

{
"coord":{"lon":-122.42,"lat":37.78},
"sys":{"type":3,"id":56874,"message":0.0953,"country":"United States of America","sunrise":1422630884,"sunset":1422667881},
"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],
"base":"cmc stations",
"main":{"temp":286.75,"humidity":69,"pressure":1017.843,"temp_min":286.75,"temp_max":286.75},
"wind":{"speed":2.16,"deg":276.502},
"clouds":{"all":0},
"dt":1422585485,
"id":5391959,
"name":"San Francisco",
"cod":200
}

This JSON string contains the weather information, we'll have to write some software to extract only what we need.

Arduino Code

In the Arduino code we will extract the values of the "description" string, "Sky is Clear"; "temp", 286.75 (in Kelvins); and "humidity", 69 (in %RH). To extract these values all we have to do is use the find(xxx) function where xxx will be the characters before the values we are trying to extract, we will then continue reading the remaining values using read() until we have read all the values. The way we know when we have read all the values is by reading in a for loop until the character ' " ', ",", and "," for description, temperature, and humidity respectively have been found.

Upload the code below to your Arduino and open the serial monitor window once the it's done uploading.

#include <SPI.h>
#include <EthernetV2_0.h>
 
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
char serverName[] = "api.openweathermap.org";
 
 
// 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;
#define W5200_CS  10
#define SDCARD_CS 4
void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
  pinMode(SDCARD_CS,OUTPUT);
 digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
   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 /data/2.5/weather?q=San%20Francisco,us 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:
  while(client.available()) {
 
     // get the short weather description
     if(client.find("description\":\"")){
       String description = "";
       for(char c = ' '; c!='\"'; c = client.read()){ // description ends with a quote "
       description+=c;
       }; 
       Serial.print("Description: ");
       Serial.println(description);
     }
 
     // get the temperature now
     if(client.find("temp\":")){
       Serial.print("Temp: ");
       String temp = "";
       for(char c = ' '; c!=','; c = client.read()){ // temperature ends with a comma ","
       Serial.print(c);
       }; 
 
       Serial.print(temp);
       Serial.println(" Kelvins");
     }
 
     // get the humidity
     if(client.find("humidity\":")){
       Serial.print("Humidity: ");
       String hum = "";
       for(char c = ' '; c!=','; c = client.read()){ // humidity ends with a comma ","
       hum+=c;
       }; 
 
       Serial.print(hum);
       Serial.println(" %RH");
     }
 
  }
 
  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
 
    // do nothing forevermore:
    while(true);
  }
}

The serial monitor window should print the following:

Weather data for San Francisco U.S. provided by the OpenWeatherMap API.

Example 5: Android App Communication With Shield

We've made a native Android app you can use to send HTTP data from a phone to the Ethernet shield. This app will send a pin number, depending on which button you press, to the Ethernet shield. When the Arduino gets the pin number it will toggle that pin and send the state of the pin back to the phone.

The Android app you can use to control the Arduino's pins through the WiFi or Ethernet Shield.

Android App Code:

Download the Android app (an Android Studio project) from this link:

File:EthernetShieldLEDControl.zip

Arduino Code and Circuit:

The code you need to upload to the Arduino is the one used in "Example 3: Control The Arduino's Digital Pins From a Webpage Served by The Shield" of this WiKi page. The circuit is also the same.

The actually also works with our WiFi shield since all it does is send HTTP requests, you watch a video about it here:

Android App for LED Control Over WiFi or Ethernet

Example 6: Chat Sever With Another Device/Terminal

The Ethernet shield can have a concurrent connection with another device to be able to send and receive data. In this example we'll show you how to use the shield to create a chat service. The chat service will send data from the Arudino's serial communication terminal to another PC/client's terminal (you can use the same PC you use for your Arduino if you like).

Download a TCP Terminal:

Download and install RealTerm, a utility terminal that will allow use to connect to the WiFi shield.

Arduino Code:

The code works like this:

  1. Connect the shield to the access point to obtain an IP address
  2. When a client's terminal sends data to the Arduino:
    1. If this is the first time print "We have a new client" in the Arduino's terminal, and print "Hello, client!" to the client.
    2. If this is not the first time a message was sent simply print the text sent in the Arduino's terminal.
  3. When you type something in the Arduino's terminal and press the "Enter" key:
    1. Read the string and print in the Arduin's terminal and send/print it to the client.

Upload the code below to your Arduino board and open the Arduino's serial communication terminal, the shield's IP address should be printed. Also do not close the Arduino's serial comm. window.

#include <SPI.h>
#include <EthernetV2_0.h>
 
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
 
 
// telnet defaults to port 23
EthernetServer server(23);
boolean alreadyConnected = false; // whether or not the client was connected previously
#define W5200_CS  10
#define SDCARD_CS 4
void setup() {
  pinMode(SDCARD_CS,OUTPUT);
 digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
  // initialize the ethernet device
  if(Ethernet.begin(mac)!=0){
    Serial.println("Could not connect to router");
  };
  // 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  
      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);
    }
 
  }
 
  // read data from the serial comm window and send it to the terminal client
  if(Serial.available()>0)
  {
   char c = Serial.read();
   server.write(c);
   Serial.write(c);
  }
 
}

Client Terminal Settings:

Open RealTerm and enter the Ethernet shield's IP address and port as shown in the image below, then click the "Open" button. The "Connected" square should be green to signal a successful connection to the Arduino's terminal.

Terminal settings: Where and how to enter the IP address and port.

Start Chatting:

In RealTerm go to the "Send" tab, enter the text you would like to send to the Arduino's terminal followed by "\r\n" and press the "SendASCII" button. You can also send messages from the Arduino's terminal to the client's terminal (RealTerm). The images below show a chat example's ouput:

The chat as seen on the terminal program.
The chat as seen in the Arduino serial comm window.

Example 7: How To Use The microSD card

The microSD card slot is connected to the Arduino's SPI port with the CS line on digital pin 4. This means that the shield is compatible with the Arduino's default SD card library and you can find numerous examples for it online.

We do provide an example you can use in our library, the example will write the Arduino's analog pin values on the SD card as well as display them on a webpage.

To see this example:

  1. In the Arduino IDE go to File->Examples->Ethernet_Shield_W5200->WebServerWithSD
  2. Insert a microSD card into the shield's microSD card slot and upload the code
  3. Don't forget to change the IP address to one that your router is able to assign, or modify the code to allow the router to auto-assign one as described in "Example 1: How To Connect To an Internet Access Point / Router".
  4. Now open the Arduino Serial monitor window and in a web browser visit the Ethernet shield's IP address, the analog pin values should be displayed and updated on the browser and will also be written to the SD card.

The important thing to keep in mind while using both the SD card and Ethernet functions of the shield is to deselect the SD card when using the Ethernet function

digitalWrite(SDCARD_CS, HIGH); // deselects SD card from SPI port.

Application 1: Home Forecast Weather Station

We can make some great applications by combining the Ethernet shield with others. The application we're going to make here is an internet connected weather forecast station, you will be able to see any city's weather for the day in a touch screen.

Internet connected weather forecast station

The Touch Screen:

The touch screen we'll be using is Seeedstudio's 2.8 TFT Touch Shield V2.0.

How We Obtain Weather Data:

We'll obtain San Francisco, US' weather information the same way we did in "Example 4: Request Weather Information From Any City in The World (Shield as Web Client)", that is using the OpenWeatherMap API which we will then display on the touch shield.

Software Libraries:

In addition to the Ethernet shield's software libraries we'll make use of touch shield's libraries which you can download from the "Resources" section in this wiki.

WiKi: 2.8 TFT Touch Shield V2.0

Arduino Code:

  • Remove all power sources from your Arduino board.
  • Stack the Ethernet shield on the Arduino, then stack the TFT Touch shield on the Ethernet shield.
  • Now power up your Arduino and upload the code below

The weather data for San Francisco, U.S. should be displayed on the TFT touch shield and update every 10 seconds, the first time it might take a while (1 minute) since the Ethernet shield is initializing.

#include <SD.h>
#include <SPI.h>
#include <Streaming.h>
#include <EthernetV2_0.h>
 
#include "TFTv2.h"
 
const int PIN_SD_CS = 4;                        // pin of sd card
 
// Ethernet
#define W5200_CS  10
// 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[] = "api.openweathermap.org";
 
EthernetClient client;
 
 
void setup()
{
 
  Serial.begin(9600);
  // deselect the SD card
  pinMode(PIN_SD_CS,OUTPUT);
  digitalWrite(PIN_SD_CS,HIGH);
 
  Tft.TFTinit();
 
  drawHeaders();
 
  TFT_BL_ON;
 
 
  // Ethernet
  // 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 /data/2.5/forecast/daily?q=san%20francisco,us&mode=json&units=imperial&cnt=1 HTTP/1.0");
    client.println();
  } 
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
 
 
}
 
void loop()
{
 
  String day = "";
  String morning ="";
  String evening ="";
  String night = "";
  String description = "";
 
  while(client.available()) {
 
     // get the day temp
     if(client.find("day\":")){
       for(char c = ' '; c!=','; ){ // data data ends with a comma ","
        c = client.read();
        day+=c;
       }; 
     }
 
 
 
     // get the night temp
     if(client.find("night\":")){
       for(char c = ' '; c!=',';){ // night data ends with a comma ","
        c = client.read();
        night+=c;
       }; 
     }
 
 
     // get the evening temp
     if(client.find("eve\":")){
       for(char c = ' '; c!=',';){ // evening data ends with a comma ","
         c = client.read();
        evening+=c;
       }; 
     }
 
 
     // get the morning temp
     if(client.find("morn\":")){
       for(char c = ' '; c!='}'; ){ // morning data ends with a  "}"
        c = client.read();
        morning+=c;
       }; 
     }
 
 
     // get the short weather description
     if(client.find("description\":\"")){
 
       for(char c = ' '; c!='\"';){ // description ends with a quote "
        c = client.read();
        description+=c;
       }; 
     }
  }
 
  // Draw the red text (weather data)
  if(description.length()>0)
  {
    Tft.fillScreen(0, 240, 0, 320, BLACK); // clear the screen
    drawHeaders();
 
    // the strings need to be changed to arrays because that is what the drawString function requires.
    char d[day.length()];
    day.toCharArray(d,day.length());
    Tft.drawString(d,75,58,2,RED); // day
 
    char m[morning.length()];
    morning.toCharArray(m,morning.length());
    Tft.drawString(m,96,87,2,RED); // morning
 
    char n[day.length()];
    night.toCharArray(n,night.length());
    Tft.drawString(n,90,143,2,RED); // night
 
    char e[evening.length()];
    evening.toCharArray(e,evening.length());
    Tft.drawString(e,80,113,2,RED); // evening
 
    char des[description.length()];
    description.toCharArray(des,description.length());
    Tft.drawString(des,30,233,2,RED); // description
  }
 
  // disconnect from the server if the server has disconnected
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
 
  }
 
  delay(10000); // update every 100 seconds
  // start a new weather request
  if (client.connect(serverName, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /data/2.5/forecast/daily?q=san%20antonio,us&mode=json&units=imperial&cnt=1 HTTP/1.0");
    client.println();
  } 
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}
 
// This functions draws the text in green.
void drawHeaders()
{
  Tft.drawString("Temp.(C)",10,10,4,GREEN);
  Tft.drawString("Day:",10,58,2,GREEN); // day
  Tft.drawString("Morn:",10,87,2,GREEN); // morning
  Tft.drawString("Night:",10,143,2,GREEN); // night
  Tft.drawString("Eve: ",10,113,2,GREEN); // evening 
}

If you would like to change the units to the metric system use the following URL in your code:

/data/2.5/forecast/daily?q=san%20francisco,us&mode=json&units=metric&cnt=1

Related Reading

Depending on the type of project you are working on you might have to learn a couple of different web languages. To help you get started we recommend the following website(s):

Resources

Related Projects

It's a pity that we don't have any demo about Ethernet Shield in the Recipe yet.

Post your awesome project about Ethernet Shield to win $100 Coupon! Please feel free to contact us: recipe@seeed.cc


Here we introduce some projects about LinkIt ONE.

What is LinkIt ONE

Linkit-one-page.jpg

The LinkIt ONE development board is an open source, high performance board for prototyping Wearables and IoT devices.

It's based on the world's leading SoC for Wearables, MediaTek Aster (MT2502) combined with high performance Wi-Fi (MT5931)

and GPS (MT3332) chipsets to provide you with access to all the features of MediaTek LinkIt.

It also provides similar pin-out features to Arduino boards, making it easy for you to connect to various sensors, peripherals, and Arduino shields.


LinkIt ONE IoT Demo

Seeed-recipe-77-20141020151546.jpg

This is an IoT demo make by LinkIt ONE.

With this demo, we can:

  • Display household temperautre, humidity, luminosity, volume control data collection on OLED screen
  • Cloud service, data uploaded to Cloud platform Xively, real-time monitoring
  • Data retention for reviewing how data changes over time
  • Remote control Household Appliances by sending a message
  • Table Lamp, 3D Printing, controlled by your phone


I want to make it.


Pringles Can antenna with a LinkIt ONE

5515ae26588ec.jpg

Make a focused antenna with a pringles can.

I want to make it.

More Awesome Projects by LinkIt ONE



Share Your Awesome Projects with Us

Born with the spirit of making and sharing, that is what we believe makes a maker.

And only because of this, the open source community can be as prosperous as it is today.

It does not matter what you are and what you have made, hacker, maker, artist or engineers.

As long as you start sharing your works with others, you are being part of the open source community and you are making your contributions.

Now share your awesome projects with us on Recipe, and win a chance to become the Core User of Seeed.

  • Core Users, are those who show high interests in Seeed products and make significant contributions on Recipe.
  • We cooperate with our Core Users in the development of our new product, this, in another word, the Core Users will have the chance to experience any new products of Seeed before its official launch, and in return we expect valuable feedback from them to help us improve the product performance and user experience. And in most cases when our Core Users have some good ideas of making things, we'll offer hardware pieces, PCBA services as well as technical support. Besides, further commercial cooperation with the Core Users is highly possible.

Get more information about Core User please email to: recipe@seeed.cc




Support

  • Forum: Please visit our forum and post your questions here if you have any problem about products.

Licensing

This documentation is licensed under the Creative Commons Attribution-ShareAlike License 3.0 Source code and libraries are licensed under GPL/LGPL, see source code files for details.

Personal tools
Namespaces

Variants
Actions
Bazaar
Navigation
Collections
Toolbox