Arduino webserver loading .htm .css and .js files

Hi All,

I am trying to make a webserver with the arduino uno + ethernet shield + SD card. The html, css and jpg files are fine and are loading perfectly but not when I add the .js file. I am not sure why so I have made a “simple” .htm with .css and .javascript code.

Can someone help me to do the arduino code which will work with this three simple files? Once, I have this working in my computer I will add more features and so on. I have tried many tutorials with no luck.


HTML code (hello.htm)

Hello World

Hello World


CSS code (hellocss.css)

h1.basic {
font-size: 1.3em;
padding: 5px;
color: #abcdef;
background: #123456;
border-bottom: 3px solid #123456;
margin: 0 0 4px 0;
text-align: center;
}


JAVASCRIPT code (hellojava.js)

function popup() {
alert(“Hello World”)
}

Thank very much for your help,
Adrian.

I am trying to make a webserver with the arduino uno + ethernet shield + SD card.

And no code? I think you're bound to be disappointed.

Can someone help me to do the arduino code which will work with this three simple files?

What have you got now? What is the client requesting? What is the client? How are you dealing with the request(s)?

adriangs: I have tried many tutorials with no luck.

A search for Arduino web server should have turned up hundreds, probably thousands of hits, including many with working code for you to try. I'd be surprised if there weren't working examples right here in the playground.

Thank you very much for your replies.

I have tried so many tutorial and I was trying to get a “new” arduino code but the code I have got so far is:


Arduino Code:

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

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

// MAC address from Ethernet shield sticker under board
byte mac = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 200); // 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 hello.htm file
if (!SD.exists(“hello.htm”)) {
Serial.println(“ERROR - Can’t find index.htm file!”);
return; // can’t find index file
}
Serial.println(“SUCCESS - Found hello.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++;
}
Serial.println(HTTP_req); //print to serial monitor for debuging
// 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 /hello.htm”)) {
client.println(“HTTP/1.1 200 OK”);
client.println(“Content-Type: text/html”);
client.println(“Connnection: close”);
client.println();
webFile = SD.open(“hello.htm”); // open web page file
}
else if (StrContains(HTTP_req, “GET /hellocss.css”)) {
client.println(“HTTP/1.1 200 OK”);
client.println(“Content-Type: text/css”);
client.println(“Connnection: close”);
client.println();
webFile = SD.open(“hellocss.css”); // open css page file
}
else if (StrContains(HTTP_req, “GET /hellojava.js”)) {
client.println(“HTTP/1.1 200 OK”);
client.println(“Content-Type: text/javascript”);
client.println(“Connnection: close”);
client.println();
webFile = SD.open(“hellojava.js”); // open css page file
}
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 = 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;*
    }

Some code that uploads a .js file. Use the code tag # to put your code in a code box.

//zoomkat 2/26/13
//SD server slider test code
//open serial monitor to see what the arduino receives
//browser address will look like http://192.168.1.102:84/servosld.htm when submited
//for use with W5100 based ethernet shields
//put the servosld.htm, slider.js, bluev_sl.gif,
//and bluev_bg.gif on the SD card
//download flies at:
// http://web.comporium.net/~shb/pix/servosld.htm
// http://web.comporium.net/~shb/pix/slider.js
// http://web.comporium.net/~shb/pix/bluev_bg.gif
// http://web.comporium.net/~shb/pix/bluev_sl.gif
// 

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

#include <Servo.h> 
Servo myservoa, myservob, myservoc, myservod;  // create servo object to control a servo 
Servo myservoe, myservof, myservog; // myservoh not used due to lack of another free pin
String readString, pos;

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 102 }; // ip in lan
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(84); //server port

//////////////////////

void setup(){

  Serial.begin(9600);

  // disable w5100 while setting up SD
  pinMode(10,OUTPUT);
  digitalWrite(10,HIGH);
  Serial.print("Starting SD..");
  if(!SD.begin(4)) Serial.println("failed");
  else Serial.println("ok");

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

  //delay(2000);
  server.begin();
  Serial.println("Ready");

  myservoa.attach(2);  //the pin for the servoa control
  myservob.attach(3);  //the pin for the servob control
  myservoc.attach(5);  //the pin for the servoc control
  myservod.attach(6);  //the pin for the servod control 
  myservoe.attach(7);  //the pin for the servoa control
  myservof.attach(8);  //the pin for the servob control
  myservog.attach(9);  //the pin for the servoc control
  //myservoh.attach(10);  //the pin for the servod control 

}

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; 
          //Serial.print(c);
        } 
        //if HTTP request has ended
        if (c == '\n') {

          ///////////////
          Serial.println(readString); //print to serial monitor for debuging

            //select proper header for file to be sent to browser

          client.println("HTTP/1.1 200 OK"); //send new page
          if(readString.indexOf("servosld") >=0) {
            client.println("Content-Type: text/html");
            client.println(); 
          }

          if(readString.indexOf("slider") >=0) {
            client.println("Content-Type: application/x-javascript");
            client.println(); 
          }

          if(readString.indexOf("bluev") >=0) {
            client.println("Content-Type: image/gif");
            client.println(); 
          }

          //select file to send to browser
          if(readString.indexOf("servosld") >=0) {
            File myFile = SD.open("SERVOSLD.HTM");
            if (myFile) {

              byte clientBuf[64];
              int clientCount = 0;              

              while (myFile.available()) 
              {
                clientBuf[clientCount] = myFile.read();
                clientCount++;

                if(clientCount > 63)
                {
                  client.write(clientBuf,64);
                  clientCount = 0;
                }                
              }
              if(clientCount > 0) client.write(clientBuf,clientCount);            
              myFile.close();
            }
          }

          if(readString.indexOf("slider") >=0) {
            File myFile = SD.open("slider.js");
            if (myFile) {

              byte clientBuf[64];
              int clientCount = 0;              

              while (myFile.available()) 
              {
                clientBuf[clientCount] = myFile.read();
                clientCount++;

                if(clientCount > 63)
                {
                  client.write(clientBuf,64);
                  clientCount = 0;
                }                
              }
              if(clientCount > 0) client.write(clientBuf,clientCount); 
              myFile.close();
            }
          }

          if(readString.indexOf("bluev_sl") >=0) {
            File myFile = SD.open("bluev_sl.gif");
            if (myFile) {

              byte clientBuf[64];
              int clientCount = 0;              

              while (myFile.available()) 
              {
                clientBuf[clientCount] = myFile.read();
                clientCount++;

                if(clientCount > 63)
                {
                  client.write(clientBuf,64);
                  clientCount = 0;
                }                
              }
              if(clientCount > 0) client.write(clientBuf,clientCount); 
              myFile.close();
            }
          }

          if(readString.indexOf("bluev_bg") >=0) {
            File myFile = SD.open("bluev_bg.gif");
            if (myFile) {

              byte clientBuf[64];
              int clientCount = 0;              

              while (myFile.available()) 
              {
                clientBuf[clientCount] = myFile.read();
                clientCount++;

                if(clientCount > 63)
                {
                  client.write(clientBuf,64);
                  clientCount = 0;
                }                
              }
              if(clientCount > 0) client.write(clientBuf,clientCount); 
              myFile.close();
            }
          }

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

          //process GET string request from client and and position servo

          pos = readString.substring(8, 12); //get the first four characters         
          //Serial.println(pos);
          int n = pos.toInt();  //convert readString into a number   
          Serial.println(n); 
          Serial.println();

          if(readString.indexOf("?0") >0) myservoa.writeMicroseconds(n);
          if(readString.indexOf("?1") >0) myservob.writeMicroseconds(n);
          if(readString.indexOf("?2") >0) myservoc.writeMicroseconds(n);
          if(readString.indexOf("?3") >0) myservod.writeMicroseconds(n);
          if(readString.indexOf("?4") >0) myservoe.writeMicroseconds(n);
          if(readString.indexOf("?5") >0) myservof.writeMicroseconds(n);
          if(readString.indexOf("?6") >0) myservog.writeMicroseconds(n);
          //only seven servo pins, so back to myservoa for testing
          if(readString.indexOf("?7") >0) myservoa.writeMicroseconds(n);

          //clearing string for next read
          readString="";
          pos="";
        }
      }
    }
  } 
}

The html, css and jpg files are fine and are loading perfectly but not when I add the .js file.

What does this mean? What serial output do you see? What does the page source code actually look like?

I have also tried this code and I can't make it work. I am looking for a simple code which works with these three file and once it is working I will add more staff in the code.

PaulS: I have the website working in the browser but when I click on the button it is not responding. The code is not loaded in the browser.

Thank you very much

I have also tried this code and I can't make it work. I am looking for a simple code which works with these three file and once it is working I will add more staff in the code.

I retried my code and it worked as expected with IE. Have you tried putting your files on a regular web server and testing to see if your html page works?

Hi Zoomkat, did you try to use your code with these three files and it is working? Because, I am trying this and I can't.

I have the three files in the root of the sd card. I have tried to change your code with my files names and didnt work. Also, I have tried to change my files names to servosld.htm and slider.js and it not working either.

Can you please pass me the code you are using??

many thanks in advance

Perhaps your .js file is corrupt or some other issue. I load files on my micro SD via a pc. The below code is the same as I previously posted except it is not optimized for fast uploading (but easier to read). Also in the header for the code I previously posted are the links for the files I used. If desired, you should be able to download those files, put them on your SD card, adjust the code for your router settings, and exactly duplicate what I’ve done (you don’t actually have to have any servos to test the code) to see if it works for you.

//zoomkat 1/26/13
//SD server slider test code
//open serial monitor to see what the arduino receives
//address will look like http://192.168.1.102:84/servosld.htm when submited
//for use with W5100 based ethernet shields
//put the servosld.htm, slider.js, bluev_sl.gif,
//and bluev_bg.gif on the SD card
//files at http://web.comporium.net/~shb/servoslider.htm page


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

#include <Servo.h> 
Servo myservoa, myservob, myservoc, myservod;  // create servo object to control a servo 
Servo myservoe, myservof, myservog;
String readString, pos;

byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 
  192, 168, 1, 102 }; // ip in lan
byte gateway[] = { 
  192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 
  255, 255, 255, 0 }; //subnet mask
EthernetServer server(84); //server port

//////////////////////

void setup(){

  Serial.begin(9600);

  // disable w5100 while setting up SD
  pinMode(10,OUTPUT);
  digitalWrite(10,HIGH);
  Serial.print("Starting SD..");
  if(!SD.begin(4)) Serial.println("failed");
  else Serial.println("ok");

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

  //delay(2000);
  server.begin();
  Serial.println("Ready");
  
  myservoa.attach(2);  //the pin for the servoa control
  myservob.attach(3);  //the pin for the servob control
  myservoc.attach(5);  //the pin for the servoc control
  myservod.attach(6);  //the pin for the servod control 
  myservoe.attach(7);  //the pin for the servoa control
  myservof.attach(8);  //the pin for the servob control
  myservog.attach(9);  //the pin for the servoc control
  //myservoh.attach(10);  //the pin for the servod control 

}

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; 
          //Serial.print(c);
        } 
        //if HTTP request has ended
        if (c == '\n') {

          ///////////////
          Serial.println(readString); //print to serial monitor for debuging
         
         //select proper header for file to be sent to browser
           if(readString.indexOf("Submit") >=0) { //don't send new page
           client.println("HTTP/1.1 204 Zoomkat");
           client.println();
           client.println(); }
           
          //client.println("HTTP/1.1 200 OK"); //send new page
          if(readString.indexOf("servosld") >=0) {
          client.println("HTTP/1.1 200 OK"); //send new page          
          client.println("Content-Type: text/html");
          client.println(); }

          if(readString.indexOf("slider") >=0) {
          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: application/x-javascript");
          client.println(); }
          
          if(readString.indexOf("bluev") >=0) {
          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: image/gif");
          client.println(); }
          
          //select file to send to browser
          if(readString.indexOf("servosld") >=0) {
            File myFile = SD.open("SERVOSLD.HTM");
            if (myFile) {
              while (myFile.available()) {
                client.write(myFile.read());
              }
              myFile.close();
            }
          }

          if(readString.indexOf("slider") >=0) {
            File myFile = SD.open("slider.js");
            if (myFile) {
              while (myFile.available()) {
                client.write(myFile.read());
              }
              myFile.close();
            }
          }

          if(readString.indexOf("bluev_sl") >=0) {
            File myFile = SD.open("bluev_sl.gif");
            if (myFile) {
              while (myFile.available()) {
                client.write(myFile.read());
              }
              myFile.close();
            }
          }

          if(readString.indexOf("bluev_bg") >=0) {
            File myFile = SD.open("bluev_bg.gif");
            if (myFile) {
              while (myFile.available()) {
                client.write(myFile.read());
              }
              myFile.close();
            }
          }

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

          //process GET string request from client and and position servo
          
          pos = readString.substring(8, 12); //get the first four characters         
          //Serial.println(pos);
          int n = pos.toInt();  //convert readString into a number   
          Serial.println(n); 
          Serial.println();
          
          if(readString.indexOf("?0") >0) myservoa.writeMicroseconds(n);
          if(readString.indexOf("?1") >0) myservob.writeMicroseconds(n);
          if(readString.indexOf("?2") >0) myservoc.writeMicroseconds(n);
          if(readString.indexOf("?3") >0) myservod.writeMicroseconds(n);
          if(readString.indexOf("?4") >0) myservoe.writeMicroseconds(n);
          if(readString.indexOf("?5") >0) myservof.writeMicroseconds(n);
          if(readString.indexOf("?6") >0) myservog.writeMicroseconds(n);
          //only seven servo pins, so back to myservoa for testing
          if(readString.indexOf("?7") >0) myservoa.writeMicroseconds(n);

          //clearing string for next read
          readString="";
          pos="";
        }
      }
    }
  } 
}

Hi Zoomkat, this code is working now perfectly with these three files in the root of the sd card. I still need to understand what I was doing wrong but it is fine.

I was ready stuck on this and now I can continue coding.

Thank you, thank you, thank you all very much for your help.

Adrian.

Hi everybody :slight_smile:

I’m a Newbie and French and i would like to know if anyone has the original files used in the code of @zoomkat!

The files is:

  • servosld.htm
  • slider.js
  • bluev_sl.gif
  • bluev_bg.gif

I use this code to test and see if i could finally solve my problem of loading css and js files.
The problem is solved with this code, thanks a lot @zoomkat !

Is it possible to load an SVG file?

I’ve add this piece of code but it still does not work.
One idea to help me? !!

          if(readString.indexOf("logo") >=0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: image/svg+xml");
            client.println();
          }

...

          if(readString.indexOf("logo") >=0) {
            File myFile = SD.open("logo-arduino.svg");
            if (myFile) {
              while (myFile.available()) {
                client.write(myFile.read());
              }
              myFile.close();
            }
          }

I'm a Newbie and French and i would like to know if anyone has the original files used in the code of @zoomkat!

The files are contained in a zip file attached to the below post.

http://forum.arduino.cc/index.php?topic=279849.msg1970392#msg1970392

Thanks a lot @Zoomkat