Basic Arduino Web Server

The Arduino, Arduino Ethernet shield and micro SD card are used to make a web server that hosts a web page on the SD card. When a browser requests a web page from the Arduino web server, the Arduino will fetch the web page from the SD card.

Creating the Web Page

Because the web page is to be stored on the SD card, it must first be created using a text editor and then copied to the SD card.

Web Page Editor

A text editor such as Brackets can be used – it is available to download here. Brackets has syntax highlighting and will automatically close HTML tags for you which makes web page editing easier. It is possible to use any other text editor, even Windows Notepad.

Web Page

Create the following web page in a text editor. When you save the text file, give it the name: index.htm

<!DOCTYPE html>
 <html lang="en-us">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <head>
 <title>Arduino -  Ethernet Shield Web Server</title>
 <link rel="stylesheet" href="css/Style.css">
 </head>
  <body>
 <div class="wrapper" >
 <div class="Logo" ><a title="Studio Pieters" href="https://www.studiopieters.nl"><img alt="" src="Images/Studio_Pieters_Logo.png"></a>
 </div>
 <H1>WEBDUINO SERVER</H1>
 <H4>If you can see this page, Arduino&#8482; Wireless Shield is installed on your Arduino&#8482; and everything is working.</H4>
 <H4>This web page is hosted from the Arduino&#8482; SD card server.</H4>
 </div>
  <div class="wrapper" >
 <div class="wrapper" >
 <p>For more information about this project go to: <a href=" https://www.studiopieters.nl/arduino-ethernet-shield-web-server/">Arduino -  Ethernet Shield Web Server.</a> </p>
 <p>Copyright &#169; 2015 <a href="https://www.studiopieters.nl/">Studio Pieters</a>. All rights reserved.</p>
 </div>
  </div>
  </div>
  </div>
  </body>
  </html>
 

Test this web page by opening it in a web browser. you now should see this.

WEBSITE

Copying the Web Page

You will need a micro SD card slot on your computer or a card reader that is capable of reading and writing a micro SD card. Insert the micro SD card into the slot on the computer or card reader that is plugged into the computer and copy the index.htm file to the micro SD card. Now plug the SD card into the micro SD card slot on the Ethernet shield.

Hardware

You should now have the micro SD card with web page copied to it inserted into the card slot on the Arduino Ethernet shield. The Ethernet shield should be plugged into a compatible Arduino and into an Ethernet cable connected to your network. The Arduino / Ethernet shield should be powered from a USB cable.

Serving Up a Web Page from the Arduino

The following Arduino sketch will enable the Arduino with Ethernet shield to serve up a single web page that can be viewed in a web browser.

Important Note!
If an uninitialized SD card is left in the SD card socket of the shield, it can cause problems with code in the sketch that is accessing the Ethernet chip. This may cause symptoms such as the sketch running once or twice, then hanging up. This is because both the Ethernet chip and the SD card are accessed by the Arduino using the same SPI bus.
/*--------------------------------------------------------------
  Project Name: Arduino -  Ethernet Shield Web Server
  Project URI:  https://www.studiopieters.nl/arduino-ethernet-shield-web-server/
  Author: Achim Pieters
  Author URI: https://www.studiopieters.nl
  Description: Arduino -  Ethernet Shield Web Server
  Version: 2.3.1
  License: GNU General Public License v2 or later
  --------------------------------------------------------------*/

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

// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   20

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 20); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80
File webFile;
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0;              // index into HTTP_req buffer

void setup()
{
  // disable Ethernet chip
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  Serial.begin(9600);       // for debugging

  // initialize SD card
  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;    // init failed
  }
  Serial.println("SUCCESS - SD card initialized.");
  // check for index.htm file
  if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
  }
  Serial.println("SUCCESS - Found index.htm file.");

  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
        // buffer first part of HTTP request in HTTP_req array (string)
        // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
        if (req_index < (REQ_BUF_SZ - 1)) {
          HTTP_req[req_index] = c;          // save HTTP request character
          req_index++;
        }
        // print HTTP request character to serial monitor
        Serial.print(c);
        // last line of client request is blank and ends with \n
        // respond to client only after last line received
        if (c == '\n' && currentLineIsBlank) {
          // open requested web page file
          if (StrContains(HTTP_req, "GET / ")
              || StrContains(HTTP_req, "GET /index.htm")) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: text/html");
            client.println("Connnection: close");
            client.println();
            webFile = SD.open("index.htm");        // open web page file
          }
          else if (StrContains(HTTP_req, "GET /css/Style.css")) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: text/css");
            client.println("Connnection: close");
            client.println();
            webFile = SD.open("Style.css");        // open the style sheet
          }
          else if (StrContains(HTTP_req, "GET images/Studio_Pieters_Logo.png")) {
            webFile = SD.open("Studio_Pieters_Logo.png");
            if (webFile) {
              client.println("HTTP/1.1 200 OK");
              client.println();
            }
          }
          if (webFile) {
            while (webFile.available()) {
              client.write(webFile.read()); // send web page to client
            }
            webFile.close();
          }
          // reset buffer index and all buffer elements to 0
          req_index = 0;
          StrClear(HTTP_req, REQ_BUF_SZ);
          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)
}

// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
  for (int i = 0; i < length; i++) {
    str[i] = 0;
  }
}

// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
  char found = 0;
  char index = 0;
  char len;

  len = strlen(str);

  if (strlen(sfind) > len) {
    return 0;
  }
  while (index < len) {
    if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
        return 1;
      }
    }
    else {
      found = 0;
    }
    index++;
  }

  return 0;
}

Using the Sketch

Copy the above sketch and paste it into the Arduino IDE. Load the sketch to the Arduino and then surf to the IP address set in the sketch with your web browser. The web page that you created should be displayed in the browser as it is served up by the Arduino SD card web server.

If everything works; – YESSSS!

giphy

Fault Finding

The only thing that can go wrong is with initializing the SD card and finding the index.htm file on the card. If the file is not on the card or does not have the exact name index.htm, then the server will not be able to display the web page.

Open up the Arduino serial monitor window to see SD card diagnostic information.

Resetting

If you were not able to connect to the Arduino, try resetting it by pressing the reset button on the Ethernet shield and then surf to the web server again.

IP Address and Address Range

Make sure that you have set the correct Arduino IP address for the address range of your network. The first three numbers of the IP address must match your network. The last number must be unique – i.e. it must be the only device on the network with that number.

Download all Files for this project on github

Do you have any questions? Leave a comment down below!

 

Pin on Pinterest0Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Buffer this pageDigg thisEmail this to someone
Flattr the authorShare on Reddit0Share on StumbleUpon0Share on Tumblr0Share on VKShare on Yummly0
  • manju nath

    brother its not worked for me am using mega2560 every thing done and even serial comm output shows GET /index.htm HTTP/1.1 when enter ip address at the browser. can you help me please to get success and sorry for my bad english

  • manju nath

    nothing shows at the browser my comm out is….

    GET /index.htm HTTP/1.1

    Host: 192.168.1.75

    Connection: keep-alive

    Cache-Control: max-age=0

    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

    Upgrade-Insecure-Requests: 1

    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36

    Accept-Encoding: gzip, deflate, sdch

    Accept-Language: en-US,en;q=0.8

    GET /favicon.ico HTTP/1.1

    Host: 192.168.1.75

    Connection: keep-alive

    Pragma: no-cache

    Cache-Control: no-cache

    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36

    Accept: */*

    Referer: http://192.168.1.75/index.htm

    Accept-Encoding: gzip, deflate, sdch

    Accept-Language: en-US,en;q=0.8

  • The best way to troubleshoot is to reduce the html code firts! Make a simple html page with only hello world and replace the index file. Now check if it works otherwise we have to dig into the arduino code.
    Good luck!