Arduino – Simple Webserver with Ethernet Shield

Using an Ethernet Shield you can run a simple web server from an Arduino.

Note: The Micro SD card must be formatted as FAT.

Functional Parts in the Project:

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

byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x3A, 0xC4 };
EthernetServer server(80);

File webPage;

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

  Serial.println(Ethernet.localIP());

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

void loop()
{
  EthernetClient client = server.available();
  if (client) { 
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) { 
        char c = client.read(); 
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();
          
          webPage = SD.open("index.htm");        
          if (webPage) {
            while (webPage.available()) {
              client.write(webPage.read());
            }
            webPage.close();
          }
          break;
          
        }
        if (c == '\n') {
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          currentLineIsBlank = false;
        }
      } 
    } 
    delay(1);      
    client.stop(); 
  }
}

HTML Page:

<p><strong>Hey LOOK. A Web Page served from an ARDUINO!!!</strong></p>
Here's a list:
<ul>
<li>one thing</li>
<li>another thing</li>
<li>yet another</li>
</ul>

<h2>Here's a picture embedded from the web!!!</h2>
<img src="https://i1.wp.com/www.failednormal.com/wp-content/uploads/2019/08/feeling-dirty.jpg">

<h2> Here's an embedded video</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/tSc4wZKfe_o" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Be the first to comment

Leave a Reply