Tag Archive: ETHERNET SHIELD


In the previous post we’ve seen how to connect the Arduino ETHERNET SHIELD to a Router directly  & upload LM35 data to Thingspeak.

What if  you do not have physical access to your Router & your Laptop is connected over WIFI to the Router. Or you cannot run a RJ45 cable from Router to Ethernet shield.

The procedure we follow is similar to the one we did for connecting Raspberry PI to Laptop.

Link here

First step is to enable SHARING of your existing internet.In my case , Laptop is connected to Router

over WIFI.

Open Control Panel –> Network & Internet –> Network & Sharing Center

Click on the existing internet connection

Image 1

On the next screen click PROPERTIES &  then SHARING

Image 2

Tick mark to ENABLE SHARING of Internet connection

Image 3

 

Now plug in the USB cable to Arduino & then connect the RJ45 Straight cable from shield to the RJ45

Port of LAPTOP.

ETH_SETUP

As soon as you connect the RJ45 cable you can see an UNIDENTIFIED NETWORK

 

Image 4

 

Click on that new Network , select PROPERTIES.

On the next screen double click on Internet Protocol version 4 (TCP/IPV4)

Image 5

You can see an IP address like 192.168.137.1.

Note that this is the new Gateway IP of the new network formed by Ethernet shield.If you do not see any IP , just select the “ Use the following IP “ &  feed in manually the IP.

 

Image 6

Now RUN  –> CMD  > IPCONFIG /ALL

to verify the IP.

Under Ethernet adapter the Gateway IP of new network is displayed.

Note that this is the GATEWAY IP & Ethernet shield will be allotted IP in this range  .

 

Image 7

Let us try some built in example codes.

Under Examples  –> Ethernet –> select  DhcpAddressPrinter

This will print the IP allotted to the Shield.

Image8

Upload the code & open up the Serial monitor.

The IP allotted to the shield here is 192.168.137.30  which is in range of new Gateway .

Image 9

 

Next example is WEBSERVER

Image 10

 

Open the WEBSERVER code .

You need to change the IP Address as 192.168.137.xxx

 

Image11

 

Here change it to 192.168.137.177 where the SERVER will be started. Note the usage of comma instead of dot between each byte.

Image 12

 

Upload the code & open the serial monitor to verify that SERVER is started.

Image 13

You can use your Browser as CLIENT.

Type in the IP 192.168.137.177 to access the server.

On the Serial monitor “Client connected “ information will apper.

Image 14

On the browser you can see the values of ANALOG Pins of Arduino.

As nothing is connected to the Analog pins , you get random values.

Image 17

 

Next example is the TELNETCLIENT

Image 2

 

Open the code.

Here Ethernet shield is used  as CLIENT & you need to change the IP of client in range with the new Gateway  192.168.137.177

Next is the IP of the SERVER . This may be another PC or Android phone connected to the same Network .

Here the SERVER is started on PC with IP 192.168.0.103

Note that this IP is in the range of Gateway of Router 192.168.0.xxx

Image 3

Scroll down further & note the PORT number on which the SERVER will LISTEN.

Here it is 10002.

Upload the code on to Arduino.

Image 4

To test the setup , you need to start a SERVER on another PC on the same network with IP 192.168.0.103

For this we use HERCULES software. DOWNLOAD HERE

Click on TCP Server tab on Hercules , feed in the port number 10002 & click LISTEN.

The server is started on PC with IP 192.168.0.103 , so , no need to enter the IP

Image 5

Now open the Serial Monitor of Arduino where SHIELD is declared as CLIENT.

You can see the “Connected..”  feed back from the Server.

Type in some characters on Arduino side , as well as Hercules side to verify 2 way communication.

Image 6

Instead of PC & HERCULES you can use your Android mobile ( to be connected over WIFI to the same Network).

On your mobile install TCP TOOLS

mobile1

Open TCP SERVER

The IP of Android device is shown with default port 8080.Click on LISTEN

In the TELNET CLIENT code you need to change the SERVER IP t from 1,1,1,1

to  192.168.0.102 & then change the port of server to 8080 & then upload to Arduino

 

mobile 2

Once code is uploaded open the Serial monitor.

On mobile you see the IP of CLIENT connected

mobile3

Test 2 way communication by typing in characters.

mobile4

 

mobile5

 

Next we shall test the code which sends LM35 Data to THINGSPEAK SERVER.

You can check my previous post for details

Upload the same code without any change in IP.

IT WORKS FOR BOTH RANGE OF ipS 192.168.0.xxx    &   192.168.137.xxx

Image 7

Open the Serial Monitor to see the data being uploaded to THINGSPEAK.

Image 8

WATCH THIS VIDEO  :

cooltext753793315   cooltext753790696

This post is a practical demo on controlling an LED from a browser.

Arduino ETHERNET SHIELD is used here. The Browser acts as a CLIENT & the SHIELD acts as a SERVER listening on HTTP PORT 80.

This demo is done on a Local Area Network .This means that the PC from where Browser is operated & the ETHERNET shield both are connected to the same NETWORK. You may have a Router in top of your Network.The Ethernet shield is connected to one of the RJ45 connector of the Router using a STRAIGHT Ethernet cable.The PC from where you start your browser is also connected to the same Router , to another RJ45 connecter or through WIFI , if your Router is WIFI enabled.

Once you connect the RJ45 cable to Ethernet shield, the left LED on RJ45 socket glows Green.This indicates a successful link made to Router.

 

IMG_20161030_153619

 

 

Image 5

Digital pin 2 is used to connect to an LED through a resistor.

Digital pin 13 is occupied by Ethernet shield , so the built in LED on pin13 cannot be used.

When the Ethernet shield is connected to the Router an IP address is allotted by DHCP of the Router.As it is Dynamic & keeps changing on every boot up , we assign the IP using the code :

byte ip[] = { 192, 168, 0, 150 };

Note that , this IP should be in the same range of your Network.

To know the range , Open Network sharing center

Click on your connection & then the DETAILS tab

Here you can see the Gateway IP & IPV4 of your PC.You should assign an IP in the same range

In my case the gateway IP is 192.168.0.1

So I’m assigning the IP of Ethernet shield by changing the last byte of the address , say, 192.168.0.150

Image 1

 

Here is the sketch used in this demo :

————————————————–

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 0, 150 }; // IP address in LAN – need to change according to your Network address
byte gateway[] = { 192, 168, 0, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port

String readString;
int ledPin = 2;

void setup(){

    pinMode(ledPin, OUTPUT); //pin selected to control
    // Test LED
    digitalWrite(ledPin, HIGH); // set pin high
    delay(500);
    digitalWrite(ledPin, LOW); // set pin low
   
    //start Ethernet
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();
}

void loop(){
    // Create a client connection
    EthernetClient client = server.available();
    if (client) {
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();

                //read char by char HTTP request
                if (readString.length() < 100) {

                    //store characters to string
                    readString += c;
                }

                //if HTTP request has ended– 0x0D is Carriage Return \n ASCII
                if (c == 0x0D) {
                    client.println("HTTP/1.1 200 OK"); //send new page
                    client.println("Content-Type: text/html");
                    client.println();

                    client.println("<HTML>");
                    client.println("<HEAD>");
                    client.println("<TITLE> ARDUINO ETHERNET SHIELD</TITLE>");
                    client.println("</HEAD>");
                    client.println("<BODY>");
                    client.println("<hr>");
                    client.println("<hr>");
                    client.println("<br>");
                    client.println("<H1 style=\"color:green;\">ARDUINO ETHERNET SHIELD — LED ON/OFF FROM WEBPAGE</H1>");
                    client.println("<hr>");
                    client.println("<br>");

                    client.println("<H2><a href=\"/?LEDON\"\">Turn On LED</a><br></H2>");
                    client.println("<H2><a href=\"/?LEDOFF\"\">Turn Off LED</a><br></H2>");

                    client.println("</BODY>");
                    client.println("</HTML>");

                    delay(10);
                    //stopping client
                    client.stop();

                    // control arduino pin
                    if(readString.indexOf("?LEDON") > -1) //checks for LEDON
                    {
                        digitalWrite(ledPin, HIGH); // set pin high
                    }
                    else{
                        if(readString.indexOf("?LEDOFF") > -1) //checks for LEDOFF
                        {
                            digitalWrite(ledPin, LOW); // set pin low
                        }
                    }
                    //clearing string for next read
                    readString="";

                }
            }
        }
    }
}

——————————————————————————

  The Arduino talks to Ethernet shield over SPI Serial Peripheral Interface. So to work with the shield you need to include both the Ethernet & SPI libraries in the top of the sketch.

#include <SPI.h>

#include <Ethernet.h>

 

The next piece of information is the MAC address of the shield , usually expressed as 6 bytes.

If your Shield has the address printed , use that MAC address.Otherwise you can settle for a random 6 bytes , as it is unlikely that another device of same address exists in the same network.

The MAC address is typically included in the Arduino sketch as global array of bytes.

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

The server is assigned on  HTTP port 80

EthernetServer server(80);

PIN 2 is assigned to LED & a string variable readString is assigned to store the request.

Under void SETUP

The method begin() in the Ethernet class attempts to connect to the Network using the details passed into its arguments.

Here we pass an IP address & the Ethernet shield makes a Network connection using a STATIC IP address.

Ethernet.begin(mac, ip, gateway, subnet);

server.begin()

starts listening on the HTTP port 80

To check the IP connection press WIN Logo key +R & then type in CMD

Ping the IP address of the Shield.

If you get back result , then you’re ready to connect the client.

Image 6

On computer Networks the machines or devices play 2 different roles : CLIENT & SERVER.

For e.g a web browser is a CLIENT that connects to other machines to request web pages or files.

The device or machine that serves the information is the SERVER.

SERVERs wait until a CLIENT connects & starts conversation with them.

PORTS allow different types of messages to be received by different pieces of software running on same server.For e.g Server software that accepts connection over FTP will usually run on port 21.WEB server software usually accepts connection over HTTP on port 80. In this demo we use he WEB SERVER.

Now open up the browser on a PC which is in the same network as Shield.

Type in the address 192.168.0.150

The following CLIENT REQUEST & SERVER RESPONSE happens in the background.

Client Request :

When you surf to the IP address of the Arduino server, the web browser (client) will send a request, such as the one shown below, to the server.

GET / HTTP/1.1\r\n

Host: 10.0.0.20\r\n

The information in the request will differ, depending on the browser and operating system that the request is sent from.

The \r\n characters that you see at the end of every line of text in the request are non-visible characters (non-printable characters). \r is the carriage return character and \n is the linefeed character (or newline character).

The last line of the request is simply \r\n without and preceding text. This is the blank line that the Arduino sketch checks for before sending a response to the client web browser.

In other words, the sketch reads every character from the above request and knows when the end of the request has been reached because it finds the blank line.

Server Response :

After receiving the request for a web page from the client, the server first sends a standard HTTP response and then the web page itself.

The response sent from the Arduino is as follows:

HTTP/1.1 200 OK\r\n

Content-Type: text/html\r\n

Connection: close\r\n

\r\n

Again the non-visible characters \r\n are shown in the above response.

The println() function in the the sketch automatically adds the \r\n characters to the end of each line. The empty println() function at the end of the HTTP response simply sends the \r\n with no text in front of it.

The above request and response are part of HTTP

Web Page

After the server has sent the HTTP response, it sends the actual web page which is then displayed in the browser.

The web page consists of text with HTML tags. You do not see the tags in the browser as these tags are interpreted by the browser.

The actual HTML markup tags are shown below.

————————————————-

<html><head>

<title> ARDUINO ETHERNET SHIELD</title>

</head>

<body>

<hr>

<br>

<h1 style="color:green;">ARDUINO ETHERNET SHIELD — LED ON/OFF FROM WEBPAGE</h1>

<hr>

<br>

<h2><a href="/?LEDON" "="">Turn On LED</a><br></h2>

<h2><a href="/?LEDOFF" "="">Turn Off LED</a><br></h2>

</body></html>

—————————————————–

In the Arduino sketch you can see these HTML tags sent using

client.println command

Now the browser displays the WEB PAGE sent as response from the Server.

Click on

Turn On LED   -  to see the LED going ON

Turn Off LED   – to make the LED OFF

indexOf String function is used to search for the string LEDON or LEDOFF.

The indexOf function returns a –1 if it doesn’t find the wanted string.This function is used to make the LED ON or OFF accordingly.

0Image 2

 

Image 3

 

Image 4

 

Instead of LED you can connect a Relay board & then control any home device through the contacts of the Relay.The above setup is the basic to start with Home Automation.

This demo is done on Local Area Network .It can be extended to Internet of Things through Port Forwarding & DDNS set up which is explained in another post.

ethernet1

 

Watch this support Video :

 

The Arduino board can be connected to the Internet using this Ethernet Shield which is based on the

WIZNET W5100 Ethernet chip . The Wiznet W5100 provides a network (IP) stack capable of both TCP and UDP.

WIZNET W5100 is the classic one , widely used by Arduino.CC .

WIZNET W5500 is used by Arduino.ORG & is referred as Ethernet shield 2.

We shall use the classic Ethernet shield W5100 in this post.

The shield has long pin headers to plug on the Arduino (UNO or MEGA). Other shields can be stacked on top of this board.There is an onboard micro-SD card slot, which can be used to store larger files.

The Ethernet Library is used to write sketches which connect to the internet using the shield. You need not download the library , as it is inbuilt in Arduino IDE.

The on-board micro SD card reader is accessible through the SD Library. Both the SD card reader & Ethernet board work on SPI bus .

The shield also includes a reset controller, to ensure that the W5100 Ethernet module is properly reset on power-up.

This board is different from the economy version using ENC28J60 device.The library for this ENC is different , ETHERSHIELD library hosted by NANODE project.Libraries are different for WIZNET board & ENC board.

Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega.

On both boards, pin 10 is used to select the W5100 and pin 4 for the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, 53, is not used to select either the W5100 or the SD card, but it must be kept as an output or the SPI interface won’t work.

As the W5100 and SD card share the SPI bus, only one can be active at a time. If you’re not using one of the peripherals in your program, however, you’ll need to explicitly deselect it. To do this with the SD card, set pin 4 as an output and write a high to it. For the W5100, set digital pin 10 as a high output.

The shield provides a standard RJ45 Ethernet jack.A straight RJ45 cable is used to connect the shield to the Router.

A RESET  button is on the shield which resets both the W5100 and the Arduino board.

The shield contains a number of informational LEDs:

  • PWR: indicates that the board and shield are powered
  • LINK: indicates the presence of a network link and flashes when the shield transmits or receives data
  • FULLD: indicates that the network connection is full duplex
  • 100M: indicates the presence of a 100 Mb/s network connection (as opposed to 10 Mb/s)
  • RX: flashes when the shield receives data
  • TX: flashes when the shield sends data
  • COLL: flashes when network collisions are detected

Apart from these LED s , there are 2 more LEDs seen below the RJ45 jack.When Ethernet cable is inserted from a working Router , you can see these LEDs glowing below the RJ45 jack, one glows steadily & the other blinks as per data flow.

The examples in this section will all make use of the Arduino Ethernet Library.This library comes with Arduino, so no downloading or installing required

You can see the examples under File –> Examples –> ETHERNET

eth1

 

The Ethernet library allows the Arduino to turn into one of two Ethernet devices: a client or a server. Turning your Arduino into client allows you to connect to and request data from servers.

Another  example included with Arduino’s Ethernet library is WebServer.  This sketch sets up the Arduino as a server device, and hosts up a webpage whenever a client connects to it. The webpage is simple – it shows the status of the analog pins.

Open the WEBSERVER sketch

Webserver is a simple sketch which will display on a web browser, the data gathered from the analogue inputs. However don’t upload it yet, it needs a slight modification.

You need to specify the IP Address of the Ethernet shield – which is done inside the sketch. This is simple, go to the line:

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

eth5

 

You can alter it to match your own setup. For example, in my home the router’s IP address is 192.168.1.1, the pc is assigned 192.168.1.6 , the tablet is assigned 192.168.1.3  , .. As the IP address is in the range 192.168.1.xxx , I just leave this to 192.168.1.177

You also have the opportunity to change your MAC address.As we use only one shield , we can leave this as it is.

To know the IP address , go to Control panel –> Network & Internet –> Network & Sharing Center

Click on your Internet connection .On the next window click Details to see the IPV4 address of your PC.

eth3

 

 

eth4

 

You can also use a IP SCANNER tool to know all the IP address allotted by your Router

http://www.advanced-ip-scanner.com/download.php?lng=en

eth7

 

Now upload the sketch to your Arduino.

Open your web bowser & type in the IP address 192.168.1.177:80 , the port address 80 is default for HTTP.Hence you need to type just the address 192.168.1.177 in the URL bar ,skipping the :80 part.

The web browser will query the ethernet shield, which will return the values from the analogue ports on the Arduino board.As such we’ve not connected anything to the Analog pins of Arduino, you get random values refreshed every second.

 

eth6

 

Remember , this is from a local browser & not from outside world.If you like to see the webserver from anywhere in the world , you need to PORT FORWARD your Static IP address to this local IP address 192.168.1.177 .This is set inside the Router’s configuration.

If your IP is not Static (mostly Dynamic which changes on every reboot) , you need to register with a service like www.noip.com

For more details of port forwarding , consider reading this post & video

https://alselectro.wordpress.com/2015/07/04/port-forwarding-part-2-solution/

https://www.youtube.com/watch?v=CyjWgqS8z2w

 

A simple sketch to print out the Gateway IP, IP of your Ethernet board, DNS is given below :

//<code>

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

byte mac[] = { 0x00, 0xC3, 0xA2, 0xE6, 0x3D, 0x57 };

void setup() {

Serial.begin(9600);
while (!Serial);
Serial.print(“Establishing network connection… “);

if (Ethernet.begin(mac) == 0) {
Serial.println(“FAILED!”);
}
else {
Serial.println(“OK!”);

Serial.print(“IP Address: “);
Serial.println(Ethernet.localIP());

Serial.print(“Default Gateway: “);
Serial.println(Ethernet.gatewayIP());

Serial.print(“Subnet Mask: “);
Serial.println(Ethernet.subnetMask());

Serial.print(“DNS Server: “);
Serial.println(Ethernet.dnsServerIP());
}
}

void loop() {
}

//</code>

 

Upload the sketch & open the Serial monitor to see the result.

ETH9

 

Example Sketch 2 : Display a web page from Arduino

 

———————————

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177); // change IP address according to your network
EthernetServer server(80);  // create a server at port 80
void setup()
{
Ethernet.begin(mac, ip);  // initialize Ethernet device
server.begin();           // start to listen for clients
}

void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {        // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {   // client data available to read
char c = client.read(); // read 1 byte (character) from client
// last line of client request is blank and ends with \n
// respond to client only after last line received
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”);
client.println();
// send web page
client.println(“<!DOCTYPE html>”);
client.println(“<html>”);
client.println(“<head>”);
client.println(“<title>Arduino Web Page</title>”);
client.println(“</head>”);
client.println(“<body>”);
client.println(“<h1>Hello from Arduino!</h1>”);
client.println(“<p>A web page from the Arduino server</p>”);
client.println(“</body>”);
client.println(“</html>”);
break;
}
// every line of text received from the client ends with \r\n
if (c == ‘\n’) {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != ‘\r’) {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1);      // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
}
———————————————————