Arduino Web Server Tutorial

Want to learn how to use the Arduino + Arduino Ethernet shield as a HTTP web server? There are many technologies that must come together to be able to make the Arduino able to host web pages. The most basic configuration requires HTTP and HTML. This can further be enhanced by adding CSS, JavaScript and AJAX.




The Arduino can produce web pages from within the Arduino sketch or host web pages that are stored on the SD card (there is a micro SD card socket on the Arduino Ethernet shield). These web pages can be configured to control and monitor hardware from a web browser on any Ethernet network that the Arduino is connected to.

This multi-part tutorial explains how to use the Arduino as a web server step-by-step. The tutorial starts with the basics and then introduces the technologies needed by using easy to understand practical examples.

The tutorial consists of the following parts:

542 thoughts on “Arduino Web Server Tutorial

  1. Hello,

    Would it be possible to post an article about controlling the same switch with Arduino and Ethernet shield but having the webpage hosted on an external server instead of having it on arduino?

    Thanks

    • Hi,
      Do you mean that you want to interface the switch to a PC and run the PC as a server using server software such as Apache?
      Do you have in mind to interface the switch to the PC using an Arduino?

      • Practically I’d want to controll Arduino from a page hosted on a PC with Apache and PHP.

        In the example you posted, the page is hosted on Arduino.

        I’d like to have the webpage on a PC with Apache because the graphic part could be much more attractive instead of a simple page created through the arduino sketch.

        Thanks

        • You could host the web pages on the SD card on the Arduino Ethernet shield, then you can develop the pages using your normal web page software and load them to the SD card. This would be like the first simple SD card example in the tutorial: http://startingelectronics.com/tutorials/arduino/ethernet-shield-web-server-tutorial/SD-card-web-server/

          There will be more SD card hosting coming up in the tutorial series.

          If you want to stick with your idea of having a separate host on a PC, then you will need to set the Arduino up as a client and not a server.

          • I need to stick with the idea to have the web gui hosted on a webserver as I need to controll a bunch of arduinos through it.

            I just needed a simple example like the one you’ve posted (one button on the webpage and one physical switch) but the webpage must be hosted on a webserver. Thanks for your answers 😉

          • Im looking for doing exactly the same, have a webpage in a server to control over it Arduino, for example: i want to put a temperature setpoint and “push it” to Arduino, i was thinking in a loop that checks for changes in the webpage

  2. Hello,

    First of all, i like too much these tutorials. I want to ask you if is it possible to make a tutorial that it can control a LED (similar to Part 5: Arduino Web Server LED Control) but from Internet.

    Thanks.

    • Hi Ricardo
      Glad to hear that you are enjoying the tutorials. I will see if I can answer your request and add it to the tutorial series. I can’t promise anything immediately as I am very busy.

  3. Hello,

    I am testing the Part 7: Manually Reading a Switch using AJAX tutorial, and i want to know exactly what do these sentences do:

    client.println(“if (this.readyState == 4) {“);
    client.println(“if (this.status == 200) {“);

    Thanks in advance.

    • Hi Ricardo
      if (this.readyState == 4) {
      Checks the status of a request, readyState can contain one of these values:
      0 = uninitialized
      1 = loading
      2 = loaded
      3 = interactive
      4 = completed
      4 represents a completed Ajax call

      if (this.status == 200) {
      Checks the status of the call to make sure that it is 200. A value of 200 means that the call succeeded.

  4. Hello,

    I am using the Part 7: Manually Reading a Switch using AJAX tutorial, and besides to get the “this.responseText;” to update the “Switch State:” text, at the same time i also want to get the background color of the “Get Switch State” button without refreshing the complete web page.

    For example, if the text is “Switch State: ON” the button background color turns “Green” and if the text is “Switch State: OFF” the button background color turns “Red”. I am fighting a lot with this and i can’t to get it.

    Thanks in advance.

  5. very interesting website..

    Q: how can the text code be edited for the webpage to display 2 separate checkboxes for controlling 2 seperate LEDs.
    Been fighting whole weekend but cannot see where LED2 is defined for the checkbox name

    thanks.

    • Just add a new checkbox: copy the current line of code (<input type=”checkbox” …., etc.) and paste it below the existing one, between the opening and closing <form> tags. Be sure to give the new checkbox a different name, you can give it a different value too if you want. Now when you click the new check box, a different name will be sent in the HTTP request. In the Arduino sketch, check for the different text and then toggle the second LED from that.

      Hope this helps…

  6. Pingback: Changing Text and Button Color using AJAX and the Arduino Web Server | Starting Electronics Blog

  7. Pingback: Switching LEDs on from a Web Page using Arduino | Starting Electronics Blog

  8. Hello,

    I tested the Part 4: Arduino SD Card Web Server tutorial, and i ask you how can i call several web pages from the index.html, and how can i navigate from these web pages?. Are the web pages in the SD card designed with the normal html syntax?

    Can you make a web server with several web pages as a reference example.

    Thanks in advance.

    • Multi-page hosting on the SD card is still coming up in the tutorial series.
      Yes, the pages on the SD card are made with normal HTML.

  9. Congratulations on fantastic tutorials. I would like to know is it possible to create plot on web page from csv source. I.e., arduino saves sensor values to csv file on sd card, arduino webserver then creates web page and part of it is plot of this file.

    • Hi Timotej and thanks.
      I am sure it is possible to create a csv file and then send the data from it for display on a web page. I will be writing more on using the SD card soon, so will look at it then. If it is too complicated I might make it into a project at some stage. Can’t promise anything immediately as I have lots of work to do.

  10. Hi
    No question just wanted to thank you for this great information you have supplied on this website. i read each one as soon as they come out.

    Thank you

    Andy uk

  11. Great tutorials, thanks for spending your time on this.
    Everything you explain really works, so far so good.
    I tried to use the automatic AJAX to drive a gauge but I get an NaN error on the gauge because it receives a string and not a number. I tried to solve this with the “parseFloat()” on the Arduino and in javascript but I can’t get it working,

    Could you explain how to drive such a gauge with AJAX on an Arduino ?
    The gauge I use is shown here
    http://www.wwvalue.com/web-design/jquery/pure-javascript-and-html5-canvas-gauge-canvgauge.html

    • Hi Hans. Thanks for an interesting question.
      It looks like parseFloat() is the correct way to convert a string to a number for the gauge – I have only looked at the guage very briefly though. I will spend some more time on this and let you know what I come up with.

      • Thanks for you reply, I asked several “expert”people simultaneously and they fixed it.
        I will put the working code on the Arduino forum where I also posted this question and where you replied.
        The major difference (as far as I understood) with your example is that you use ajax to change the html code but that the for the gauge I need to send it a value (no html involved). No need to spend any more time on this.

        • Ok, thanks. I was thinking of adding this gauge to one of the parts of the tutorial because it looks like something nice that people can use.

          • Great idea, I spent a lot of time to find out that it is not that easy, and needed expert help to get it working. Now I must figure out how to use javascript buttons to control my arduino, once that’s understood I can start making the GUI for my home automation.
            Keep working on this tutorial, great stuff!

        • Could you please provide a link to the Arduino forum post you’re talking about? I’d like to implement this and would probably need to see how it’s done. Thanks!

  12. First, very nice work, help me a lot.
    I am trying to host a web server loaded from SD card, and I am experiencing connection problems. First of all I am using Uno R3, Ethernet Shield W5100, 2Gb SD Card formated FAT32.

    First I had to set pin10 as output and in HIGH state, otherwise it didn’t work well.
    When I load the web page for the first time, it seems ok, but when I try to refresh, Arduino get stuck. I managed to ignore the “favicon” request that comes right after the main request from Chrome or Firefox. But i could not solve it. Can you please help me?
    Thanks and I send you more details as you need them.

    • I don’t have the same hardware as you, so I can’t test it. Try asking on the Arduino forum where you should find someone who has used the same hardware as you.

      • 99 % chance you run out of memory on the UNO board, I had the same problem and without changing the code, running it on a Mega solved all the problems.

    • Are you closing the file after you’re done reading/writing it? That’s one way to eat up a lot of memory.

      webFile.close();

      • Hi again! 🙂
        I’m having a problem with the Part 11: Arduino SD Card Web Server – Displaying Images . I use the exact 3 files in zip but the image wont appear :(. If I open the index.htm on a desktop browser it works fine, but when served on the arduino the image doesn’t show. I’ve tried renaming it on the SD an on the index.htm but still don’t work. The SD card is working fine I guess, because I can succesfully serve a full webpage.

        What could be the problem??

        Thanks!!

          • Hey, thanks for answering! I don’t know why, but now its working ok! 😀 I didn’t change anything, its strange, but it’s working.

            Thanks!

  13. Hi

    Great Website. Im currently working on my Final year Project and would like some assistance please.
    i have not worked much with arduino just recently i have dived into it. in part 14 you are able to read from switches and display it on the webpage by using ajax-xml as your backround script language to update the statuses. Is is safe to assume that u can modify the code to be able to switch on/off for example LEDS by using buttons on the webpage saved on the SD card .

    • You should be able to modify the example to add buttons. This multi-part tutorial is not complete yet – there will be an example of using both Arduino input and output with Ajax. This will be added soon…

      • hi

        i was actually using a Diligent Chipkit Uno and because the library is not exactly the same i found it difficult just to run your code on the chipkit uno.

        So i took a long drive into different town that had stock, and bought my self Arduino Due and Ethernet shield.

        So i copied your code to the arduino due and managed to modify it to turn 4 channel relay on/off.
        But what i notice is that there is a delay, maybe couple seconds when switching on or off. im not sure if its because im using “if then statements” and maybe changing it to case_switch statements will improve the delay? or is it cause of the hardware ? its running 84mhz cpu. advise me please

        my next step is to implement a temperature sensor that will log the temperature in a file/database and display it on the webpage when the user wants to view it , is that feasible?

        and also do you think the guage example could be modified so that it display the current temp?

        Sorry for so many questions

        Again brilliant Site, thank you so much for sharing you knowledge, much appreciated

        thanks

        Del

        • Hi Del
          The delay with the relays: I have found that sometimes the web browser and operating system can cause a delay. I have had the fastest results from Linux. I don’t think that the problem is the on the Arduino software side. The delay can also be caused by traffic on the network. Remember that Ethernet is not a real-time network.

          Logging the temperature to a file should be no problem. To display the logged temperatures on a web page you will just need to send the values from the file as part of the web page. You may want to use the HTML5 canvas to display it as a graph. It all depends on how good you want to get with HTML/JavaScript.

          The gauge example is perfect for modifying to display temperature. You just need to convert the analog temperature value to the correct units and set up the gauge to display the desired range.

          Hope this helps…

  14. Hi,
    I’ve really learned a lot from your tutorial. Thanks heaps for investing so much of your time to help others. 🙂
    I am new on the Arduino scene, but have gotten your “eth_websrv_SD_Ajax_in_out” up and running it works great !
    I just have one question. When power is applied to the Arduino server after it’s been off for a while (a few minutes), the I/O server does not boot up untill I press the Reset button ? I have tried on a Duemillenove and on a UNO ….
    Is there some way to fix this, so as to self re-boot after power failure ?
    Cheers,
    Mario

    • Hi Mario
      Thanks for your feedback 🙂
      The Arduino should reset when power is switched on. Have you experienced this problem with any other sketch running on the Arduino or only with the web server sketch?
      Do you still have a web browser connected to the web server when you power up?

  15. Hi,
    Thanks for the speedy reply.
    In order to give you some detailed feedback, I did some more systematic testing.
    I discovered that the the problem was somewhat random.
    every now an then it would boot up OK ?
    I figured that this must be a Hardware problem, not software.
    I tried another Ethernet Shield and the problem is gone 🙂
    Once again…
    Many thanks for your great work.
    Mario

  16. Hi. I tried Part 4 but the is no respond or no content display in my browser. Whats wrong with the sketch?

    The arduino can read index.htm in SD.

    Thank you.

    • Hi Yusri
      What web browser are you using and have you tried a different browser?
      Also, put some debug code that writes a message to the serial port after:
      if (c == ‘\n’ && currentLineIsBlank) {
      to see if you are receiving a HTTP request from the web browser. (Check if the message comes up in the Arduino serial monitor window)

      • Hi,

        I tried IE and Chrome.

        I have troubleshoot and found something I do not understand. The first byte my arduino read (webFile.read()) from html file is Ÿ . I did not know where it come from and it not exist in index.htm file.

        So, what I did was I reject the first byte before I continue the other bytes.

        I also found another problem after i resolved the above problem, I can not do refresh to the page for the second time onward.

        I only got the content after I reset my arduino. The second time i tried again, no content exist in the page.

  17. I’ve tried the gauge control example and it looks great, but works not at all over WiFi, I get a blank page. I’ve tried a couple of browsers, on my phone and tablet, and tried increasing the timeout value. Just wondering if anyone else has experienced this problem?

  18. Hi, in relation with the 17th tutorial, in my project i have programm web pages and several javascript functions, and i realized that i run out the RAM memory, so i need to maintain the principal HTML page in the flash memory and store a javascript file with the javascript functions in the SD Card to free RAM memory.

    Can you tell me how can i create an external javascript file store in the SD Card, and how to call these functions from the HTML page in the flash memory, is it possible you put a brief example, maybe using parameters?. I was trying it and i can’t got it.

    Thanks in advance,

    Ricardo

    • Hi Ricardo
      You need to include the JavaScript file in your HTML page. To include a JavaScript file called global.js, you will need to put the following line in the head section of the HTML:
      <script type=”text/javascript” src=”global.js”></script>

      You will also need to handle the HTTP request when the web browser asks for the JavaScript file.

  19. Hi.

    I have a problem. When i start to initialize the SD card it is always fails. Even if i reset the board or unplug the power (USB). But if i remove the card and put it back again when the Arduino is powered it works fine until the next reset or power up. I did the SD card examples (SD info, Read/Write) and it’s ok. I tried with Duemilanove and Mega 2560 and W5100.

    Any idea what should i do???

    Thanx in advance.

      • Hi.
        I have checked many forums and i find the source of the problem. Because both the SD and the W5100 are “speaking” on the SPI, when i used Your code the W5100 was the first in the line to initialize itself and then the SD. So what i have done is swap the SD and the W5100. Now first i set the pin 10 to output and after HIGH to “Pause” the W5100 until the SD initializing.

        Here is the code:

        void setup()
        {

        Serial.begin(9600); // for debugging
        //Disable W5100 till SD set up
        pinMode(10,OUTPUT);
        digitalWrite(10,HIGH);
        // 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

          • I have to say Thank You for You, because you have made this tutorial and it is saved to me tons of free time to create my project.

            So thanks a lot again and all the best 😀

  20. Hello,

    When I test “Part 15” I get the message in my Chrome browser:

    This XML file does not appear to have any style information associated with it. The document tree is shown below.

    988

    It seems that there is no index.htm request coming in. The Arduino states that the index.htm is available on the SD card. The only difference with the tutorial is that I’m using the official Arduino Wifi shield

    I actually expecting the gauge to show up. Does somebody know what I do wrong? Thanks.

  21. Hi there,
    I can’t seem to load the example with the SD card and image. I dont understand why it isnt working. It loads well from the desktop but once in the sdcard it doesnt. Ive tried chrome and IE and no luck. Much thanks.

  22. Hi ,
    firstly thanks for the great tutorials. I’m new to Arduino development and these have made life easier. I have a similar problem to those above. I have test and run your SD basic web server (Part 4) but in Part 15
    I can’t seem to load the example with the SD card and image. It appears to be stuck in the client.write(webFile.read()); since I have Serial write statements before and after this call. I have tried the initialisation of SD and ethernet as mentioned above but no joy. Any thoughts?

  23. Hi;
    firstly thanks for the great tutorials. I have a similar problem with tutorial Part 15. The webpage does not load. It appears to read from the SD card but cannot get past the writing index.htm to generate a webpage. It looks like it is stuck in client.write(webFile.read()); I have run tutorial Part 4 fine and tried the SD/Ethernet initialisation mentioned above but no joy. Any thoughts?

    • Set up a counter in the loop:
      while(webFile.available()) {

      Write the count value to serial port and check the value in the Arduino serial monitor window to see if it is sending any data and how many bytes.

      Which Arduino and Ethernet shield are you using?

  24. On the i/o sd card web server i changed the checkboxes for buttons in the page and the sketch and i also loaded a different page but when i try to turn the leds that were from the checkboxes i need to press a lot of times the buttons on the web page until the arduino lights them, but with the other leds i dont have any problem, i dont know if its a sram problem or hardware, do you know what could be happening?

    • I can only suggest that you check your code again carefully. I don’t think it can be hardware if the other LEDs are working properly.

      • The leds that were controlled by buttons in the sketch are working normally but he leds that were controlled by checkboxes y changed them to be controlled by buttons too, but as i said i have to press them on the web pages a lot of times to turn them on

  25. A question.
    If i don’t want to use any kind of Java or AJAX, something like a browser with no kind of updates, only HTML and CSS.What is the solution to display buttons and inputs ?..the html code need to be saved on SD card.
    TNX.

  26. Hi!
    Thanks for the great tutorials! This code (part 16) was the first arduino webserver that runs stable for many days serving multiple request inside&outside LAN.

    Is there a solution for pvh’s problem?
    see above
    “This XML file does not appear to have any style information associated with it. The document tree is shown below…”
    I’m experiencing the same thing with chrome, IE, FF using Uno R2 and W5100 and a good working SD.

    Also can you give some clues for basic authentication ? As Part 19 maybe?
    Thanks!

    • Hi kisskovi
      I have not had the same problem as you are experiencing so can’t do fault finding on it.

      What do you mean by authentication, do you want to password protect the pages on the web server?

      • I think some username/password like login will give some level of comfort. Just enough to accidental visitors of the server can’t fiddle with the buttons and other settings.

        I belive my problem with the gauge comes from a rather nasty router. Right now, after some runs with the basic webClient example, it refuses to connect and hangs after a while…

  27. Does anyone know how to fix the sd webpage problem. I can’t get jpeg pictures to load. Please help this is for a school project. Im using arguing no with official Ethernet shield. None of the stuff in this blog is helping. Thanks a lot.

    • Hello,
      First of all thanks a lot for this nice and very helpfull tutorial (great job);
      I ‘m facing same issue in sd web page problem with Arduino Uno Rev3 + Ethernet shield MEGA Compatible. I can’t get HTML + jpeg pictures on my computer with Chrome, IE and or/Firefox
      All comments, ideas or feedback are welcome
      Thanks in advance
      Regards

      Jean Luc
      On my serial port, I received these inputs:
      Initializing SD card…
      SUCCESS – SD card initialized.
      SUCCESS – Found index.htm file.
      GET / HTTP/1.1
      Host: 192.168.0.51
      User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
      Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
      Accept-Encoding: gzip, deflate
      Connection: keep-alive

      GET /favicon.ico HTTP/1.1
      Host: 192.168.0.51
      User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
      Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
      Accept-Encoding: gzip, deflate
      Connection: keep-alive

      GET /favicon.ico HTTP/1.1
      Host: 192.168.0.51
      User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
      Accept: image/png,image/*;q=0.8,*/*;q=0.5
      Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
      Accept-Encoding: gzip, deflate
      Connection: keep-alive

      GET /favicon.ico HTTP/1.1
      Host: 192.168.0.51
      User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
      Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
      Accept-Encoding: gzip, deflate
      Connection: keep-alive
      .

  28. I had also trouble with the picture and the gauge example with an arduino uno R2…
    strange but swapping to a mega R3 it worked instantly (with the same ethershield, same files on the same SD card, same network, same ip etc…)

    could it be a ram shortage on the uno?

    • It could possibly be the RAM, but this is strange as I developed the sketches on an Arduino Uno (original before any revision board) – there should be no RAM size difference between the Unos.
      If you feel like experimenting, then cut the HTTP message short as had to be done in part 16 to save RAM and see if the other examples work on the Uno.

  29. Hi,
    Thanks for this tutorial, it really helped me to understand a lot of things and develope my project. you ve done a great job.
    I used the part 10 in order to link some pages, but not with SD card. so i would appreciate if you can explain me exactly how this “(HTTP_req.indexOf(“GET / “) > -1” works. I have read about indexOf in arduino site but still cannot make it work properly.

    I have another issue as well that i would like an advance from you if you have time. I want to make my arduino working in a loop (something like,open some leds reacting to some sensors) by entering one of my pages (lets say, if you enter “autoMode” page) and continue this loop evel if the user leave the page.But when the user ask for something else by clicking another link or open again the main page,then the program can exit from the loop.
    I hope you understand … thank you in advance

  30. Hi michalis, thanks for your kind words. I am glad that you found the tutorial useful.
    To answer your questions:
    if ((HTTP_req.indexOf(“GET / “) > -1)
    HTTP_req is holding the received HTTP request from the web browser at this time and is an Arduino String object. The above line checks if the value returned by the String method indexOf is greater that -1 to check for the presence of the string “GET /” in the received request.

    So from part 10 of the tutorial:
    if ((HTTP_req.indexOf(“GET / “) > -1)
    || (HTTP_req.indexOf(“GET /index.htm”) > -1))
    This checks if a GET request has been received for the home page of the Arduino web server ( / = root or home page) or the home page by file name: index.htm
    If indexOf returns 0 or greater, then the string passed to it exists in the string object. By checking if indexOf returns a number greater than -1, we are checking for a number that is 0 or greater as zero is greater than minus one.

    Your second question:
    If you want the Arduino to loop through some code when a page is visited, just use a variable in the Arduino as a flag. When the page is visited, set the flag. The flag can control the loop, but the loop must also check for new HTTP requests and clear the flag when one is received so that the Arduino exits the loop.

    Hope this helps.

    • hi, thanks for the immediate response.
      about my second question you helped me a lot and i found the way to do what i needed.

      Now about the first question, the truth is that i had understood the way is working the indexOf, but still cannot fix the problems.
      The problems i face are: 1.when i am entering the page from my phone,it shows me the second page instead of the main and i can do nothing actually. 2.from my pc sometimes i need to douple click the buttons or the links to do the job. I am adding the code,maybe you can see something since you are more experienced.
      thanks again.

      #include
      #include
      #include
      #define LED 5
      #define LED2 8
      byte mac[] = { };
      IPAddress ip();
      EthernetServer arduserver(80);
      String HTTP_req = “”;
      int value=0;

      void setup(){
      Ethernet.begin(mac, ip); // initialize Ethernet device
      arduserver.begin(); // start to listen for clients
      Serial.begin(9600); // for debugging

      pinMode(LED , OUTPUT);
      pinMode(LED2 , OUTPUT);
      }
      void loop(){
      EthernetClient client = arduserver.available();
      if (client) { // got client?
      value=1;
      boolean currentLineIsBlank = true;
      while (client.connected()) {
      if (client.available()) { // client data available to read
      char c = client.read();
      HTTP_req += c;
      Serial.print(c);
      if (c == ‘\n’ && currentLineIsBlank) {
      client.println(“HTTP/1.1 200 OK”);
      client.println(“Content-Type: text/html”);
      client.println(“Connnection: close”);
      client.println();
      if (HTTP_req.indexOf(“page2”) > -1) {
      webPage2(client);
      value=0;
      }
      else if (HTTP_req.indexOf(“page3”) > -1) {
      webPage3(client);
      }
      else if(HTTP_req.indexOf(“Lr=ON”) >-1){
      digitalWrite(LED , HIGH);
      webPage3(client);
      }
      else if(HTTP_req.indexOf(“Lr=OFF”) >-1){
      digitalWrite(LED , LOW);
      webPage3(client);
      }
      else if(HTTP_req.indexOf(“Br=ON”) >-1){
      digitalWrite(LED2 , HIGH);
      webPage3(client);
      }
      else if(HTTP_req.indexOf(“Br=OFF”) >-1){
      digitalWrite(LED2 , LOW);
      webPage3(client);
      }
      else webMainPage(client);
      HTTP_req = “”; // empty the string
      break;
      }
      if (c == ‘\n’) {
      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);
      client.stop(); // close the connection
      } // end if (client)
      else if ((!client) && (!value)){
      do {
      autoModeLoop();
      }
      while (client);
      }
      }
      // send HTML for the main page
      void webMainPage(EthernetClient maincl){
      maincl.println(“”);
      maincl.println(“”);
      maincl.println(“”);
      maincl.println(“Auto mode page 2.”);
      maincl.println(“Manual mode page 3.”);
      maincl.println(“”);
      maincl.println(“”);
      }
      // send HTML for the second page
      void webPage2 (EthernetClient secondcl){
      secondcl.println(“”);
      secondcl.println(“”);
      secondcl.println(“”);
      secondcl.println(“Auto mode”);
      secondcl.println(“Go back to main page.”);
      secondcl.println(“”);
      secondcl.println(“”);
      }
      //send HTML for the third page
      void webPage3 (EthernetClient thirdcl){
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“MySmartHome”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“living room”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“bedroom”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      thirdcl.println(“Go back to main page.”);
      thirdcl.println(“”);
      thirdcl.println(“”);
      }
      void autoModeLoop(){}

      P.S. I use X10, but lets say there are just LEDS

      • I just solved the problem by adding

        if (HTTP_req.length() < 20)
        HTTP_req += c;

        in order to check only the first line of client's request.
        In fact I didnt figure out what was causing the problem, but doesnt matter

        thanks again

  31. Hi.
    Thank you for sharing this tutorial, it has been very helpfull to undestand arduino Ethernet. I think i´m able now to control PWM output using a scroll bar, any suggestion?
    Keep doing such a great job!

    • Thanks Eduardo.

      I guess you will need to make the scrollbar in JavaScript. I don’t think that there is any HTML for making a scrollbar.
      Happy coding 🙂

  32. Brilliant tutorial. Thanks indeed. The following might help some people stuck like I was.
    I found that all examples that **did not use an SD card** would run once or twice then crash after a few loops with the SD card inserted. I could only reset by resetting the power!
    The behaviour was erratic. I suspected bad hardware and even ordered a new ethernet shield 🙁
    I suddenly had some inspiration, removing the SD card made all the difference. Hope this helps.

    • Thanks, Steve.
      I’m glad you brought this up. I now remember this problem and checked back on some of my earlier code that I wrote before the tutorial.

      The SD card and Ethernet chip share the SPI bus on the Arduino, so there can be problems with the uninitialized SD card interfering with the Ethernet chip. Here is the code from the setup() part of the sketch with comments:

      // disable the SD card by switching pin 4 high
      // not using the SD card in this program, but if an
      // SD card is left in the socket, it may cause a problem
      // with accessing the Ethernet chip, unless disabled
      pinMode(4, OUTPUT);
      digitalWrite(4, HIGH);

      • Gosh that was fast.

        Thanks… That’s what I’m seeing. Odd flaky behaviour with the SD card in the socket but not used. I guess, I should have read the code more carefully. If all else fails, read the instructions. (I just looked but could not find the code comments you give in your email.)

        For the other sad people like me (sniff) it could help to have a note in the main text? I’m usually careful but I got carried away with my enthusiasm. The read around was interesting though. Most people who have problems seem to blame the power supply or the Ethernet chip overheating. I ran the SD card server for days with a proper PSU and it functioned perfectly although it became pretty hot. I was convinced that the problem was in the cheap Ethernet card I was using.

        Thanks again for a tremendous set of tutorials — inspirational.

  33. Pingback: google

  34. hello, first of all I want to thank this tutorial which I have been very useful and I learned a lot. I want to consult about something, I tried the code “Arduino SD Card Web Server” and it worked perfectly, but when try “Arduino SD Card Web Server – Displaying Images” that did not work. added an output after Webfile = SD.open (“INDEX.HTM”) and throws me “0” unlike the first code that throws me 1.

    that may be what I’m doing wrong?

  35. I am building a data logging board with a 250 KSPS 16 bit analog to digital convertor. I would like to send data files to the Arduino Mega 2560 and have the files available for FTP using the Ethernet shield. File sizes would be around 1 – 2 megabyte and uploaded from the web server every 5 seconds or so. Is the Arduino system fast enough for this? Or is Arduino intended for smaller files, such as emails, small control files, etc?

    • The Arduino and Ethernet shield will be way too slow for this application. Images that are more than a few kilobytes can be seen loading when present on a web page.

  36. Thanks for this great tutorials! It learns me a lot.

    At this moment I’m searching why the linking of te pages on the SD card doesn’t work. I look with safari (firefox or opera) to arduino, but the page is left blank.
    When I do a reload, there is something beiing sent from arduino, but I can’t read what.
    Arduino can get the SD card initialized. When I load the first sketch in the tutorial that has it’s website on the SD card, index.htm gets loaded well in safari.
    Do you have a suggestion?
    Best, Sjoerd

    • Hi Rick
      Have you tried sending the output to the Arduino serial monitor window to see what is being sent to the browser?
      Which browser / os are you using and what Arduino hardware are you using?

        • In the line:
          client.write(webFile.read()); // send web page to client
          Send on the serial port instead, this should work:
          Serial.write(webFile.read());

  37. Pingback: News: Changes to Arduino Ethernet Shield Web Server Tutorial | Starting Electronics Blog

  38. Pingback: News: Solving the Arduino Ethernet Server Page Linking Problem | Starting Electronics Blog

  39. I stumbled across your site and this Arduino Web Server Tutorial in search results from Google.

    Wow. This is an amazing amount if information, and stunningly well presented!!!

    My search started, because I’m struggling with an Arduino and Ethernet Shield project; and have been searching for information.

    I would love to describe my project, and my problem; and see if someone can provide me with some insight. I’d be more than happy to contribute my final code and any circuit descriptions once I get it working.
    Is this something allowed on your site? If so, is there a place other than in the comments section of the blog for the tutorial that you’d prefer it to go?

    Thank you again for an amazing tutorial. I’ve spent the entire day on it; and will probably go through sections of it again at future dates.

    Regards,
    Monte

    • Hi Monte
      It is good to hear that you found the tutorial so useful.
      I could publish your project in the Projects section of the website if you like and give you the credit, but I would need to review your project first.
      At the moment I only have the blog comments area and Facebook where users can contribute, but no real platform for users wanting to publishing a project.

      Also note that I am busy rewriting some of the sketches for the web server tutorial because of problems that people are having when using the String class with Arduino boards that only have 2k of SRAM – see the News section on this blog for more info.

  40. Hi! If you are on reviewing your examples, please add basic html authentication, as it will give some level of security to a web enabled arduino.Thanks!

    • Hi kisskovi
      I will not be able to add authentication to the tutorial, but I will add it to my list of things to do. It will take me some time to do the research and write the code for authentication.

      • Thats ok! I did some research myself but always the same: just the webduino. So im eagerly waiting what cuod you bring uop!

        cheers,

  41. hello,
    This website is wonderful. I try to automatically display the temperature via a probe 1wire on a web browser.
    The temperature is displayed correctly once but did not update …
    But I based on your code …

    Could you look at the code below and tell me what could block?

    #include // librairie pour capteur OneWire
    #include
    #include
    #include
    #include
    #include
    #include
    #include

    // — Déclaration des constantes —
    //— déclaration du tableau d’adresse MAC —
    byte mac[] = {
    0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // valeur arbitraire

    //—- tableau de l’adresse IP de la carte Arduino
    byte ip[] = {
    192,168,0,36 };

    //—– tableau de l’adresse de la passerelle —
    byte passerelle[] = {
    192, 168, 0, 1 }; // l’adresse du PC de connexion ou de la Box

    //—– tableau du masque de sous réseau
    byte masque[] = {
    255, 255, 255, 0 }; // idem masque sous-réseau du PC : 255.255.255.0

    //—- code des instructions du capteur
    const int modeLecture=0xBE;
    const int lancerMesure=0x44;

    // — constantes des broches —

    const int broche_OneWire=2; //declaration constante de broche
    const int broche_rel01=3;
    const int broche_rel02=4;
    SerialLCD slcd(2,3);
    // — Déclaration des variables globales —

    byte adrCaptPiscine[8] = {
    0x28, 0x17, 0x8E, 0xA2, 0x04, 0x0, 0x0, 0x99}; // adresse sonde Piscine
    // byte adrCaptPiscine[8] = {
    // 0x28, 0x6C, 0xBB, 0x25, 0x02, 0x0, 0x0, 0x21}; // adresse sonde Piscine old
    byte adrCaptPac[8] = {
    0x28, 0x17, 0x8E, 0xA2, 0x04, 0x0, 0x0, 0x99}; // adresse sonde Pac
    byte adrCaptBulle[8] = {
    0x28, 0x17, 0x8E, 0xA2, 0x04, 0x0, 0x0, 0x99}; // adresse sonde Pac Bulle
    byte data[12]; // Tableau de 12 octets pour lecture des 9 registres de RAM et des 3 registres d’EEPROM du capteur One Wire
    // byte adresse[8]; // Tableau de 8 octets pour stockage du code d’adresse 64 bits du composant One Wire
    // byte adresse2[8]; // Tableau de 8 octets pour stockage du code d’adresse 64 bits du composant One Wire

    float ma_tempetf=0.0;
    String chaineRecue=””; // déclare un string vide global
    int comptChar=0; // variable de comptage des caractères reçus
    float tempPiscine=0.0;
    float tempPac=0.0;
    float tempBulle=0.0;
    char tampon[2] = {”};
    String HTTP_req; // stores the HTTP request

    // — Déclaration des objets utiles pour les fonctionnalités utilisées —
    OneWire capteur(broche_OneWire); // crée un objet One Wire sur la broche voulue

    //— création de l’objet serveur —-
    EthernetServer server(80); // crée un objet serveur utilisant le port 80 = port HTTP

    //**************** FONCTION SETUP = Code d’initialisation *****
    // La fonction setup() est exécutée en premier et 1 seule fois, au démarrage du programme

    void setup() { // debut de la fonction setup()

    // — ici instructions à exécuter au démarrage —

    slcd.begin();
    Serial.begin(115200); // initialise connexion série à 115200 bauds
    // IMPORTANT : régler le terminal côté PC avec la même valeur de transmission

    //—- initialise la connexion Ethernet avec l’adresse MAC, l’adresse IP et le masque
    Ethernet.begin(mac, ip, passerelle, masque);

    //—- initialise le serveur HTTP—-
    server.begin(); //—- initialise le serveur HTTP

    pinMode(broche_rel01, OUTPUT); //met la broche en sortie
    pinMode(broche_rel02, OUTPUT); //met la broche en sortie
    } // fin de la fonction setup()
    // ********************************************************************************

    //*************** FONCTION LOOP = Boucle sans fin = coeur du programme *************
    // la fonction loop() s’exécute sans fin en boucle aussi longtemps que l’Arduino est sous tension

    void loop(){ // debut de la fonction loop()
    Serial.println(“**** temperature Piscine **** “);
    tempPiscine = capteurMesureTemp(adrCaptPiscine); // appel de la fonction de mesure – renvoie une valeur float
    Serial.println(tempPiscine);
    Serial.println(“**** temperature Pac **** “);
    tempPac = capteurMesureTemp(adrCaptPac);
    Serial.println(tempPac);
    Serial.println(“**** temperature Bulle **** “);
    tempBulle = capteurMesureTemp(adrCaptBulle);
    Serial.println(tempBulle);
    // slcd.clear() ;
    // slcd.setCursor(0, 0);
    // print the number of seconds since reset:

    // dtostrf(tempPiscine, 5, 2, tampon);
    // slcd.print(tampon);

    if (tempBulle > 30)
    {
    Serial.println(“Temperature Bulle sup a 30 degres”);
    digitalWrite(broche_rel01,HIGH);
    digitalWrite(broche_rel02,LOW);
    } // met la broche au niveau haut (5V) – allume la LED
    else {
    Serial.println(“Temperature Bulle inf a 30 degres”);
    digitalWrite(broche_rel02,HIGH);
    digitalWrite(broche_rel01,LOW);
    } // met la broche au niveau bas (0V) – éteint la LED

    // delay(10000); // pause de 10 secondes

    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
    HTTP_req += c; // save the HTTP request 1 char at a time
    // 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: keep-alive”);
    client.println();
    // AJAX request for switch state
    if (HTTP_req.indexOf(“ajax_switch”) > -1) {
    // read switch state and send appropriate paragraph text
    GetSwitchState(client);
    }
    else { // HTTP request for web page
    // send web page – contains JavaScript with AJAX calls
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“Arduino Web Page”);
    client.println(“”);
    client.println(“function GetSwitchState() {“);
    client.println(“nocache = \”&nocache=\”\
    + Math.random() * 1000000;”);
    client.println(“var request = new XMLHttpRequest();”);
    client.println(“request.onreadystatechange = function() {“);
    client.println(“if (this.readyState == 4) {“);
    client.println(“if (this.status == 200) {“);
    client.println(“if (this.responseText != null) {“);
    client.println(“document.getElementById(\”switch_txt\”)\
    .innerHTML = this.responseText;”);
    client.println(“}}}}”);
    client.println(
    “request.open(\”GET\”, \”ajax_switch\” + nocache, true);”);
    client.println(“request.send(null);”);
    client.println(“setTimeout(‘GetSwitchState()’, 1000);”);
    client.println(“}”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“Arduino AJAX Switch Status”);
    client.println(
    “Switch state: Not requested…”);
    client.println(“”);
    client.println(“”);
    }
    // display received HTTP request on serial port
    Serial.print(HTTP_req);
    HTTP_req = “”; // finished with request, empty string
    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)

    } // fin de la fonction loop() – le programme recommence au début de la fonction loop sans fin
    // ********************************************************************************

    // ********************************************************************************

    //*************** Autres Fonctions du programme *************

    //************************** fonction d’initialisation du capteur ****************

    //————– fonction de mesure de la température —————

    float capteurMesureTemp(byte adressecapteur[8]) { //fonction qui renvoie résultat float et ne reçoit rien

    //——– variable locale de la fonction ———-
    int tempet=0; // variable pour resultat brute de la mesure
    float tempetf=0.0; // variable pour resultat à virgule de la mesure

    // XXXXXXXXXXXXXXXXXXXXXX Lancement d’une mesure et lecture du résultat XXXXXXXXXXXXXXXXXXXXXXX

    // Serial.println(“**** Acquisition d’une mesure de la temperature **** “);

    // avant chaque nouvelle instruction, il faut :
    // * initialiser le bus 1-wire
    // * sélectionner le capteur détecté
    // * envoyer l’instruction

    //——— lancer une mesure ——–
    capteur.reset(); // initialise le bus 1-wire avant la communication avec un capteur donné
    capteur.select(adressecapteur); // sélectionne le capteur ayant l’adresse 64 bits contenue dans le tableau envoyé à la fonction
    capteur.write(lancerMesure,1); // lance la mesure et alimente le capteur par la broche de donnée

    //——– pause d’une seconde —–
    delay(1000); // au moins 750 ms
    // il faudrait mettre une instruction capteur.depower ici, mais le reset va le faire

    //———- passer en mode LECTURE ————-
    capteur.reset(); // initialise le bus 1-wire avant la communication avec un capteur donné
    capteur.select(adressecapteur); // sélectionne le capteur ayant l’adresse 64 bits contenue dans le tableau envoyé à la fonction
    capteur.write(modeLecture,1); // passe en mode lecture de la RAM du capteur

    // ———– lire les 9 octets de la RAM (appelé Scratchpad) —-

    for ( int i = 0; i < 9; i++) { // 9 octets de RAM stockés dans 9 octets
    data[i] = capteur.read(); // lecture de l'octet de rang i stocké dans tableau data
    }

    //—– caclul de la température mesurée (enfin!) ———

    data[1]=data[1] & B10000111; // met à 0 les bits de signes inutiles
    tempet=data[1]; // bits de poids fort
    tempet=tempet<<8;
    tempet=tempet+data[0]; // bits de poids faible

    // — en mode 12 bits, la résolution est de 0.0625°C – cf datasheet DS18B20
    tempetf=float(tempet)*6.25;
    tempetf=tempetf/100.0;

    return tempetf;

    }
    // ————— fin de la fonction de mesure de la température ———-
    void GetSwitchState(EthernetClient cl)
    {
    cl.print("Analog A2: “);
    cl.println(tempPiscine);
    cl.println(“”);
    }
    // — Fin programme —

  42. Great Tutorials! I learned a lot. Thanks. In Article 15 – webserver gauge project. I loaded the files as stated. The serial monitors displays data as the server server serves the page. However, I get a blank page on IE, Google chrome and android phones when tested. What could be wrong? I am using the latest browsers. Thanks again in advance.

    • Hi!
      I finally found out what causes the blank page problem on part 15 – gauge display. Whats missing in the original sketch is shown below:

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

      Inserting the above code after the #include lines and before ethernet shield variables worked.
      The digital dial worked as expected. Blank page problem solved!

  43. Hi,

    i do this tuto
    http://startingelectronics.com/tutorials/arduino/ethernet-shield-web-server-tutorial/SD-card-AJAX-web-server/

    i modifie this part and it doesn’t work
    I can’t connect to the webserver
    void GetSwitchState(EthernetClient cl)
    {

    cl.print(” Température Piscine: “);
    cl.println(tempPiscine);
    cl.println(“”);
    cl.println(“Température Pompe à Chaleur / Solaire: “);
    cl.println(tempPac);
    cl.println(“”);
    cl.print(“Température Bulles : “);
    cl.println(tempBulle);
    cl.println(“”);

    if (digitalRead(7) == 1) {
    cl.print(” Chauffage solaire en marche “);
    cl.println(“”);
    } else {
    cl.print(” Chauffage solaire à l’arret “);
    cl.println(“”);
    }
    }

    When i shorten this part by deleting if (digitalRead(7) == 1) {
    cl.print(” Chauffage solaire en marche “);
    cl.println(“”);
    } else {
    cl.print(” Chauffage solaire à l’arret “);
    cl.println(“”);
    }

    or

    cl.print(” Température Piscine: “);
    cl.println(tempPiscine);
    cl.println(“”);
    cl.println(“Température Pompe à Chaleur / Solaire: “);
    cl.println(tempPac);
    cl.println(“”);
    cl.print(“Température Bulles : “);
    cl.println(tempBulle);
    cl.println(“”);

    it works …..
    it appears that the code is too long … ?
    How can i display more informations ?

    • Hello
      I tried to find a solution but can not display all the information the code actually looks too long and I can not find the solution

  44. Hello,

    When I test “Part 14 – Arduino Inputs using Ajax with XML on the Arduino Web Server″ I get the message in my Chrome, IE and Firefox browser:

    This XML file does not appear to have any style information associated with it. The document tree is shown below.

    OFF
    OFF
    276

    It seems that there is no index.htm request coming in. The Arduino states that the index.htm is available on the SD card. I’m using the official Arduino Ethernet R3 shield + Uno R3.

    Does somebody know what I do wrong?
    Thanks.

  45. Hi,

    Thanks for these great tutorials. I’ve one question concerning js gauge code inserted in part 15: gauge.js.min downloaded from Mikhus Github and the code you’ve directly inserted into html are really not comparable. How can we go from one to the other ? I would like to do the same with another javascript object but I don’t understand the transition.

    Thanks

    • Hi Jean. I checked the code at Github and it has changed since I wrote the tutorial.

      To see the code correctly, you must click the file gauge.min.js at Github, don’t try to save it. Now on the page that opens, you can right-click the “Raw” button and save the file.

      The actual JavaScript is a single line once it has been saved off Github correctly.

  46. Great Tutorial. I keep coming back to it! I’ve run most if not all of the examples. All have worked great and are a wonderful learning experience. I point my fellow ‘nerd’ friends here all the time. Anyway in Part 16 you demonstrate 2 Web Browsers concurrently connected to the Arduino. I’ve read that there is a max limit of 4 connections, (part of the ethernet chip set limitations). Is this true, or is there a way of serving more than 4 clients with any of these examples?

    • Hi Mark
      The answer is in the W5100 Ethernet chip data sheet. I have lots of work at the moment, so don’t have time to check it myself, but remember reading it there.

  47. Hi…. this link is super useful .. i like “Arduino Web Server Gauge Displaying Analog Value ” a lot. But i do not have a SD. How can I implement this without the SD . I don’t really know how as I am a beginner.

      • Yes, you can use the gauge to show temperature or any analog value.
        To port the example for use without the SD card would take a bit of work. I don’t have time at the moment.

  48. What an excellent, very well written, grouping of tutorials. I have expressed my appreciation in the form of a donation. Please accept it.

    I am picking part tutorial 16 (website buttons to toggle LED’s, includes AJAX) and modifying for my needs. I had planned to put the arduino website into an iframe on my server, but as others have pointed out, it might be a kludge this way. I am really hoping to see a tutorial where we can control each arduino from a website hosted on another box. I hope this tutorial would suggest ways to handle network related delays.

    Thanx again, Tom

    • Thanks Tom, and thank you for the donation – it is much appreciated.
      Are you wanting to control more than one Arduino from a single web page?

      • Yes, right now I seek to control multiple Arduino units from IIS running on my Win7 box. In the future, I want to figure how to get a webserver running on an android tablet so I don’t need to tie up my Win7 workstation with webserving. Is this possible now ? I am not Linux literate so that is not an option for me right now.

        One other thing about the index.htm file. Is that distinct to offload from flash and otherwise yield more space for compiled code ?

        Thanx again, Tom

        • I am sure it is possible to control the Arduinos from a web server, but it is different to what is done in the tutorial where each Arduino is a web server. It looks like you want a separate PC to be the server and then fetch data or control Arduinos attached to it over Ethernet. I remember someone else wanting to do something similar.

          The index.htm file is separate for two reasons, one reason is to free up the Arduino’s Flash memory, the other is that the web page is developed as a separate file and is easier to read and debug when it is a separate file. It becomes difficult to read in the Arduino code when it is inserted into print statements, and when you need to make some changes it ends up getting messy.

  49. I just wanted to say that this is a very well written tutorial and I enjoyed it a lot. Thanks for the dedication and keep it going 😉

  50. Hi m8! You have done an excelent job with these examples!

    I am using the example 16 and it works very nice.
    I want to make an arduino connect to the arduino server (with the code from part 16) and to read the state of the switch 2 or an analog input.

    Can you help me with the code? What to enter in the GET method? What to search for?

    Please Help ME!!

  51. Hi there! Maybe someone pointed this out, a small problem in part 9, declaring analog input:
    analog_val = analogRead(2);
    was actually:
    analog_val = analogRead(A2);
    Nothing else, I loved your work! Keep it up!

  52. Hi
    Thanks so much for the tutorials.
    They are fantastic.

    I’ve loaded your sketch from section 16 and I’ve modified it for use with a WiFi shield instead.

    I can successfully connect to my network and ping the server but when trying to open the web browser, the page takes around 5 minutes to load and sometimes not at all.

    Do you have any idea as to why this could be happening?

    The SD card initializes correctly and shows:
    Initializing SD card…
    SUCCESS – SD card initialized.
    SUCCESS – Found index.htm file.
    but the page just isn’t displaying.

    • I forgot to mention…
      I’m using an UNO R3 board and Wifi Shield.

      The Sketch is as follows:

      #include
      #include
      #include

      int status = WL_IDLE_STATUS;
      #define REQ_BUF_SZ 60 // size of buffer used to capture HTTP requests
      File webFile; // the web page file on the SD card

      char HTTP_req[REQ_BUF_SZ] = {0}; // Buffered HTTP request stored as null terminated string
      char req_index = 0; // index into HTTP_req buffer
      boolean LED_state[4] = {0}; // stores the states of the LEDs

      //Server Details

      char ssid[] = “ssid here”;
      char pass[] = “password here”;
      IPAddress ip(190, 160, 10, 10);
      WiFiServer server(80);

      void setup() {

      Serial.begin(9600); // initialize serial communication

      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
      Serial.println(“WiFi shield not present”);
      while(true); // don’t continue
      }

      WiFi.config(ip);

      // attempt to connect to Wifi network:
      while ( status != WL_CONNECTED) {
      Serial.print(“Attempting to connect to Network named: “);
      Serial.println(ssid); // print the network name (SSID);

      // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
      status = WiFi.begin(ssid, pass);
      // wait 10 seconds for connection:
      delay(5000);

      pinMode(4, OUTPUT);
      digitalWrite(4,LOW);
      SD.begin(4);

      // start the web server on port 80
      server.begin();

      }

      pinMode(6,OUTPUT);
      //pinMode(7,OUTPUT);
      //pinMode(7,OUTPUT);
      //pinMode(8,OUTPUT);

      printWifiStatus();

      }

      void loop()
      {
      WiFiClient client = server.available(); // listen for incoming clients

      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
      // limit the size of the stored received HTTP request
      // 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++;
      }
      // 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");
      // remainder of header follows below, depending on if
      // web page or XML page is requested
      // Ajax request – send XML file
      if (StrContains(HTTP_req, "ajax_inputs")) {
      // send rest of HTTP header
      client.println("Content-Type: text/xml");
      client.println("Connection: keep-alive");
      client.println();
      SetLEDs();
      // send XML file containing input states
      XML_response(client);
      }
      else { // web page request
      // send rest of HTTP header
      client.println("Content-Type: text/html");
      client.println("Connection: keep-alive");
      client.println();
      // send web page
      webFile = SD.open("index.htm"); // open web page file
      if (webFile) {
      while(webFile.available()) {
      client.write(webFile.read()); // send web page to client
      }
      webFile.close();
      }
      }
      // display received HTTP request on serial port
      Serial.print(HTTP_req);
      // 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(2); // give the web browser time to receive the data
      client.stop(); // close the connection
      } // end if (client)
      }

      // ===============================================================================================
      // Checks if received HTTP request is switching on/off relays and also saves the state of the relays
      void SetLEDs(void)
      {
      Serial.println("Something Clicked");
      // LED 1 (pin 6)
      if (StrContains(HTTP_req, "LED1=1")) {
      LED_state[0] = 1;
      digitalWrite(6, HIGH);
      }
      else if (StrContains(HTTP_req, "LED1=0")) {
      LED_state[0] = 0;
      digitalWrite(6, LOW);
      }
      // LED 2 (pin 7)
      if (StrContains(HTTP_req, "LED2=1")) {
      LED_state[1] = 1;
      digitalWrite(7, HIGH);
      }
      else if (StrContains(HTTP_req, "LED2=0")) {
      LED_state[1] = 0;
      digitalWrite(7, LOW);
      }
      // LED 3 (pin 8)
      if (StrContains(HTTP_req, "LED3=1")) {
      LED_state[2] = 1;
      digitalWrite(8, HIGH);
      }
      else if (StrContains(HTTP_req, "LED3=0")) {
      LED_state[2] = 0;
      digitalWrite(8, LOW);
      }
      // LED 4 (pin 9)
      if (StrContains(HTTP_req, "LED4=1")) {
      LED_state[3] = 1;
      digitalWrite(9, HIGH);
      }
      else if (StrContains(HTTP_req, "LED4=0")) {
      LED_state[3] = 0;
      digitalWrite(9, LOW);
      }
      }

      // ===============================================================================================
      // send the XML file with analog values, switch status and LED status
      void XML_response(WiFiClient cl)
      {
      int analog_val; // stores value read from analog inputs
      int count; // used by 'for' loops
      int sw_arr[] = {2, 3, 5}; // pins interfaced to switches

      cl.print("”);
      cl.print(“”);

      // Relay 1
      cl.print(“”);
      if (LED_state[0]) {
      cl.print(“ON”);
      }
      else {
      cl.print(“OFF”);
      }
      cl.println(“”);

      // Relay 2
      cl.print(“”);
      if (LED_state[1]) {
      cl.print(“ON”);
      }
      else {
      cl.print(“OFF”);
      }
      cl.println(“”);

      //Relay 3
      cl.print(“”);
      if (LED_state[2]) {
      cl.print(“ON”);
      }
      else {
      cl.print(“OFF”);
      }
      cl.println(“”);

      //Relay 4
      cl.print(“”);
      if (LED_state[3]) {
      cl.print(“ON”);
      }
      else {
      cl.print(“OFF”);
      }
      cl.println(“”);
      cl.print(“”);
      }

      // ===============================================================================================
      // sets every element of str to 0 (clears array)
      void StrClear(char *str, char length)
      {
      for (int i = 0; i len) {
      return 0;
      }
      while (index < len) {
      if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
      return 1;
      }
      }
      else {
      found = 0;
      }
      index++;
      }
      return 0;
      }

      // ===============================================================================================
      //For debuggin purposes
      void printWifiStatus() {
      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your WiFi shield's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      // print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
      // print where to go in a browser:
      Serial.print("To see this page in action, open a browser to http://&quot;);
      Serial.println(ip);
      }

    • Hi, I’m trying to make a robot with arduino mega 2560 Rev3 + Arduino WiFi shield, using the SD card for my HTML files so I’ve got the same problem as you,it took a lot of time for the webpage to be loaded. Do you please have got the solution.
      thanks.

  53. Friend, good night.

    Congratulations for the excellent tutorials.
    I need a help to change the tutorial 16 (Part 16 of the Arduino Ethernet Shield Web Server Tutorial).

    It is possible to separate the ajax request pins analog buttons?
    Since realized that is updated every 1 second but if you change to 10 seconds the whole screen takes 10 seconds to respond.

    Can you separate?

    Thank you and congratulations.

  54. Good night.

    Could you help me with the tutorial Part 14 of the Arduino Ethernet Shield Web Server Tutorial?

    I’ll light a LED but also do not know how to do it.
    Can you help me?

    Thank you.

  55. Hi,

    I use in my house an Arduino UNO with Ethernet Shield connected to the router that controls the lights of the house through the computer and smartphone by socket commands.

    I am now trying to create a mini Webserver by Arduino to control the lights by Smart TV also through the browser, and I’m following the instructions in Part 5.

    I adapted the code from the tutorial with the code that I already used, but I have questions in some parts:

    void loop() {

    EthernetClient client = server.available();

    // SE receber um caracter…

    delay(50);
    if (client) {

    boolean currentLineIsBlank = true;

    // guarda o caracter na string ‘msg’
    msg[0]=msg[1];
    msg[1]=msg[2];
    msg[2]=msg[3];
    msg[3]=msg[4];
    msg[4]= client.read();

    char c = msg[4]; // Lê 1 byte (caractere) do cliente
    HTTP_req += c; // Salva o pedido HTTP 1 caractere de cada vez
    if (msg[4]==’#’)
    {
    LOOKS AND EXECUTE SOCKET COMMANDS
    }
    else
    {
    while (client.connected())
    {
    if (client.available())
    {
    if (c == ‘\n’ && currentLineIsBlank)
    {
    // Envia um cabeçalho de resposta padrão HTTP
    client.println(“HTTP/1.1 200 OK”);
    client.println(“Content-Type: text/html”);
    client.println(“Connection: close”);
    client.println();
    // Envia a página
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“Arduino – Luzes da Casa”);
    client.println(“”);
    client.println(“”);
    client.println(“Luzes da Casa”);
    client.println(“Clique para Acender ou Apagar a luz.”);
    client.println(“”);
    ProcessButton(client);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    Serial.print(HTTP_req);
    HTTP_req = “”; // Termina o pedido, limpa a String
    break;
    }

    if (c == ‘\n’)
    {
    currentLineIsBlank = true;
    }
    else if (c != ‘\r’)
    {
    currentLineIsBlank = false;
    }
    } // Fim (client.available())
    } // Fim while (client.connected())

    delay(1); // Dar tempo ao navegador para receber os dados
    client.stop(); // Fecha a conexão

    } // Fim ELSE
    } // Fim client
    } // Fim Loop

    // Mudar LUZ e enviar de volta para a caixa HTML
    void ProcessButton(EthernetClient cl)
    {
    if (HTTP_req.indexOf(“luz=Quarto”) > -1)
    {
    if (digitalRead(4) == LOW)
    {
    digitalWrite(4, HIGH);
    }
    else
    {
    digitalWrite(4, LOW);
    }
    }

    if (HTTP_req.indexOf(“luz=Sala”) > -1)
    {
    if (digitalRead(5) == LOW)
    {
    digitalWrite(5, HIGH);
    }
    else
    {
    digitalWrite(5, LOW);
    }
    }

    cl.println(” “);
    }

    When making a socket connection, the Arduino would not be stuck in “While” blocking of analyzing the messages to be sent? And if I delete the “While”, the Arduino would not be resubmitting the page every time it goes by Loop?

    And in “client.stop ();”, when making a socket connection, it would also be closed?

  56. good work.
    I manage to control 4 relays with your web server (Part 16 of the Arduino Ethernet Shield Web Server Tutorial).
    The problem is that the relay module is ON when the input is LOW (when I start arduino the state of outputs are LOW so the relays are ON, and I need the relay to be off when arduino start).

    I insert this code in void setup()
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(9, HIGH);
    to force the output relays to be HIGH. It is working when i start arduino, but in the browser i have to click twice on the button for everything to become normal.
    So, can somebody help me with this problem ?

    • I solved my confusion since relay is opposite of high/low by using this.

      #define RELAY_ON 0
      #define RELAY_OFF 1

      so digitalWrite(6,RELAY_ON);

  57. Hi. Brilliant Tutorial! Thank you for your time for creating this. I’ve learned so much through it and it gave me the starting blocks with which I created an awesome looking WebGUI. I have created the WebGUI for home security & emergency response. (I live in crime-ridden South-Africa).

    I would just like to ask you if you would mind to please help pointing me in the correct direction forward? Now that I have this great website functioning on the principles you explained, I wish to compile native apps using PhoneGap or a similar compiler. There are so many options to choose from, and as a beginner I am extremely unsure which protocols, methods or general ‘strategy’ to choose from.

    If you get the time, any advice/opinion would be greatly appreciated.

    Once again, thank you very much!

    • (Just to be clear, I wish to “convert” my current website to a native app through PhoneGap or the likes. I am unsure of how to tackle data handling for this?)

  58. Great Tutorials. I have successfully completed all tutorials except Part 15: Arduino Web Server Gauge Displaying Analog Value. The webpage displays page tile “Arduino Ajax Dial” and also heading Arduino Ajax Dial & Analog (A2): but the gauge does not appear. Even though gauge.min.js is also present in the root folder of SD card alongwith index.htm

    Any help would be very much appreciated.

    Thanks.

    • The gauge code must be put into the html file. If it is put onto the SD card as a separate file and referenced or included by the html file, then you need to write the code that responds to the browser request for the file.

      • The sketch is the same you have provided in tutorial 15. This is the index.htm I am using which only adds src=”gauge.min.js” in the source tag everything else is exactly the same as given in your tutorial.

        —————–
        ———-
        gauge.min.js is copied to the root folder of SD card. The serial monitor confirms the presence of index.htm:

        Initializing SD card…
        SUCCESS – SD card initialized.
        SUCCESS – Found index.htm file.

        But somehow I have not been able to display the Gauge. Any thing I am missing here?

        Thanks for your prompt reply.

        • Getting this in the serial monitor when I access Arduino web server:

          Initializing SD card…
          SUCCESS – SD card initialized.
          SUCCESS – Found index.htm file.
          GET / HTTP/1.1
          HosGET /gauge.min.js HGET /favicon.ico HT

          • SD card is fine. Browser is requesting the .js file which the Arduino sketch does not handle – you will need to add this code.

        • Hi Tariq
          There is no code in the sketch to handle an external JavaScript file. Using an external JavaScript file for the gauge will stop it from working. You will need to add code to the sketch to handle a request from the browser for the JavaScript file so that the Arduino sends the file to the browser when requested.

          • Ok so it means the sketch for tutorial 15 doesn’t contains code for handling external Javascript gauge.min.js. But you mentioned in the tutorial that the gauge is made available to the web page by inserting the gauge code between the script tags in the head of the web page HTML code. Is it possible for you to share the code to be included in the sketch to handle the request from the browser for the external Javascript file.

            Thanks.

          • The JavaScript code between script tags allows the gauge to be embedded in the HTML page.

            I have not written any code to handle an external JavaScript file.

          • This is exactly what I have done in index.htm, by placing as suggested in your tutorial and placing the gauge.min.js on SD Card alongwith index.htm , but unfortunately the Gauge is not displayed.

            Sorry for bothering so much.

            Thanks for helping me out.

  59. I have found your tutorials very informative. I did get the webserver example with analog, switch status, checkbox and buttons working. However, I have an application where I just need the button press to turn an output on or off. When I tried to remove the other inputs and outputs from your sketch, the button did work but would not change to indicate, for example, “LED 3 is ON” even though it was on. Can you tell me how to trim down the sketch and index.htm to just have one or two buttons that will accurately reflect their status as ON or OFF?
    Thanks!

    • Hi Arniep
      You will need to follow the tutorial carefully so that you understand everything and then you will be able to make your own cusom example. I don’t have time right now to make a new example for you, but all the information that you will need to make your own project is in the tutorial.

  60. Hello, i use ajax to display temperature on a website every that updated every 2 seconds. The problem is that after two updates some part of the code appears at the website and then it stops updating. Do you know what the problem is ? Thanks !

  61. Pingback: arduino + apache :) | CaOS by iomonk

  62. Hi, hope you are fine.
    First I would like to thanks a lot for these great tutorials. I’ve learned a lot. I am trying to use the part 16 for a lighting control system. In the system the status of each lamp and the temperature are being shown. Also there are buttons for different modes (morning, evening etc.) which changes the status of the lamps. There is just buttons and no check-boxes. When the total buttons (modes and lamps) are less than 13 everything’s working perfectly, but when I add new mode which results into new ifs and request the webpage won’t be load. Do I need to use a special way for many outputs?
    Thanks again.

    • Well , I’ve found the problem. I am using arduino uno for this project which is being loaded by 85% of its memory. So it will face a stability problem as it has not that much memory to handle tasks.
      Is there any way to use the SD card as the Flash memory?!!!
      IF the answer is negative which arduino board do you suggest ? Arduino Mega or Due?
      Again THANKS A LOT for these great tutorials, right now I have a full lighting AJAX control system with your guidance.

      • Hi ashkan
        The SD card would not be able to be used as Flash memory unless you wrote some kind of operating system to handle it.

        I would suggest using the Arduino Mega. The Arduino Due works only from 3.3V and has 3.3V I/O. You could use the Due if this is not a problem and you have a new Ethernet shield that is compatible with the Due.

        • Thanks a lot for you response.
          I bought the DUE, I have the Ethernet Shield V2,
          I could read the SD card and open the webpage by removing lines:
          // disable Ethernet chip
          pinMode(10, OUTPUT);
          digitalWrite(10, HIGH);
          and using the IDE 1.5.3 .
          the web page is loaded i could see the changes of Text in the buttons, but reading the switches is the problem as they are being read once at the beginning of loading the page which is OFF for all. when i click on any buttons the output is being changed but the status is not. i have the changes of the analog input on the page. However its not correct but its being updated !!!!.
          the same sketch works fine on UNO.
          does it back to enabling and disabling the shield?
          is there any way that you could suggest? thanks.

          • I’ve changed the output pins from {2,3,5,6,7,8,9,A0,A1,A2,A3} to { 22 -32 } as the previous one was for UNO, NOW the status of the pin 22 is being shown and the “for loop” is being updated just for 22!!, also at the beginning when i define the output pins, by default all of them are being set as HIGH, so manually i have to set them LOW.
            It seems to be Completely different, the IDE 1.5.4 doesn’t work properly, 1.5.1 and 1.5 works.
            do you know any good reference for DUE?
            The reason that i bought it was the speed and the memory, but it seems that this board is quiet different in many things.

          • Hi ashkan
            Sorry, can’t help you there. I have a Due board but do not have a compatible Ethernet shield for it (and no spare time at the moment). You will need to do some searching and experimenting on your own.

          • Hi and thanks again for your response.
            i could manage to solve the analog reading problem, the clue is the time delay.
            when its more than 500ms the reading will leads to 0 after two cycles. so in the html code I’ve changed the ajax request time to 300 instead of 1000. the reading now is fine, but switch status no its not.
            if i could find anything else will share it here. hope you could suggest any different way.
            Thanks.

  63. es posible hacer un identificador para autentificar un Usuario, como usuario y password para visualizar una pagina WEB??

    is possible to make an identifier for authenticating a user, such as username and password to view a web page?

  64. Hallo.
    Thanks for this incredible tutorial. Probably the best I have ever read on an Arduino topic.
    I am going to use it in the next weeks for an RF generator we are using for Laser modulation.
    Do you have an idea how to solve the issue of connecting automatically with the Embedded Web Server at an unknown ip that was determined by DHCP?
    Anything to type or copy into my browser, a small Windows programm or javascript or…
    This would be the last little thing to make this a professional user interface for any scientific device.
    Thanks again and keep up the good work.
    Cheers,
    Eduardo

    • Hi Eduardo
      I think there may be a library that enables you to use DHCP – I looked at this a while back and vaguely remember something. Try doing some searching, you may find something. I don’t have time at the moment to look at this myself.

  65. Hi.
    I am working on the solution.
    DHCP was quite easy, just calling Ethernet.begin(mac) without ip.
    What I am testing is an UDP broadcast to reach my device at an ip which is unknow in the first moment through a specific port, f. e. 55555.
    The Device would then reply informing about it’s ip and a browser f.e. could now reach it through normal tcp/ip. That’s the plan.
    I am struggling with UDP-test-tool to send broadcast UDP packets and receive them with Arduino…

  66. Hello,
    related with Part 17, one thing you don’t explain and I consider to be quite interesting is calling .CSS and .JS files in the instead of writing all the css or js script between head tags.

    OK, easy. The problem is when serving the js file with the arduino.

    Is this right?
    client.println(“Content-Type: application/x-javascript”);

    Thx

  67. as you can leave JavaScript file outside the website. in a file. “js” and that could also load in HTML.
    Thanks very good tutorial

  68. This tutorials are really good. Could you perhaps make an tutorial on how to authentication login Before entering the SD Card Web Server I/O?

  69. hi and congratulations for that amazing and informative tutorial about arduino web server!
    well I have a query and I am wondering if you can give me a clue about it.In part 6 “reading a switch” of the tutorial arduino web server it says that the next part will explain with the help of AJAX,how we can only refresh a part of the website and not all of it.So inspired by that I thought I could do the same with my project but I am not sure if that can be done.I ve made a website where are displayed temperature measurements and from a value and on I want some buttons to appear and the user will decide to turn on or off certain devices lets say.The problem is that my page is refreshed every 10 sec because I want to take the new temperature measurements but the result is that the button is refreshed without keeping the previous state.(e.g.I turn on a led the screen shows the button on, after the website is refreshed the screen shows that the led is off although it is on)so I am wondering if I can use the AJAX to separate the website so that only the sensor part will be refreshed and the button will stay out of that.
    If that cannot be made do you think that I should use a variable that can keep the previous state of the button and put it in the refresh or a database to fix that problem?
    thanks in advance

  70. Hello,
    In part 14 I don’t get to insert in the XML file an HTML anchor. What I’m trying to do is to print in the web page a link with an image inside that changes depending on an arduino input. But the link doesn’t show neither the image.
    I don’t want to show a simple “ON” or “OFF” but a complete anchor with img tag inside
    Thanks a lot

  71. Hello,

    I too wish to control multiple arudino’s with the html file hosted on a remote web server. I have found that changing the get command address in the index.htm file works to remotely control the arduino. But…with the html file hosted remotely it does not get the analog or button status/updates. Although pressing the button or clicking the checkbox does turn on and off the LED’s.

    There must be something else that needs to be changed in order for this to work?

    This is the line I changed in the index.html. I only added the http://192.168.75.105/

    request.open(“GET”, “http://192.168.75.105/ajax_inputs” + strLED1 + strLED2 + strLED3 + strLED4 + nocache, true);

    Anyone have any ideas on what to change in order for it to get the updated status on the inputs?

  72. I have figured out how to remotely host the index.htm file on an external/remote web server.

    This will allow me to expand on the index.htm file to control multiple arduino’s from one web page over the network!

    Please reply to this post if you are interested in learning how.

    Excellent tutorial!

    Dan.

    • Thanks, Dan for your feedback and info. I am still so busy at work, that I hardly have time to read the comments. I see that there is at least one person interested in your project. Are you going to publish your project?

      • Yes, I actually found an easier way to accomplish this.

        There is one modification of code in the index.htm file as stated in an earlier post, and one modification in the arduino code.

        First modify this line in the index.htm:

        request.open(“GET”, “ajax_inputs” + strLED1 + strLED2 + strLED3 + strLED4 + nocache, true);

        to look like this:

        request.open(“GET”, “http://192.168.75.105/ajax_inputs” + strLED1 + strLED2 + strLED3 + strLED4 + nocache, true);

        where http://192.168.75.105/ is the ip address of the arduino.

        Then in the arduino code you need to add this:

        client.println(“Access-Control-Allow-Origin: *”);

        directly under this:

        client.println(“HTTP/1.1 200 OK”);

        Access-control-allow-origin allows a remote client (in this case, the remote web server) to request an xml file from the arduino’s web server. This is circumventing the default security on the web server so use this with caution. With this option on any web server or client can pull the xml file from your arduino’s web server

        Thanks,
        Dan.

        • THANKS A LOT man for sharing this solution. its amazing just by two lines. I’v been searching for month. so now the UI could be much more interesting with more features as the main process of UI is not with the Arduino.
          Thanks again.

        • Thanks Dan, much appreciated.
          I now have the server running on a Raspberry Pi and serving a faster nicer page. It has freed a lot of room on the Arduino to now add my old RF code to control some power outlets. Still cant get the second gauge to display correct data though. One gauge is fine 2 or more display ok, but not with the right data.

          Cheers and thanks again
          John

      • The above code is all I added in order to make it work. Then I setup a remote web server and put the index.htm file on it. I point my browser to that server and it pulls the data from the arudino’s web server just as if you connect to it directly.

        There is no more need for any of the sd card stuff in the code.

        Dan.

        • Hi Dan
          I have this working really well, but only if connected from the local LAN. From outside I get the webpage (served from a RaPi) but the data does not update.
          I suspect it is due to the “GET” request being directed to the LAN address of the Arduino (192.1681.130 in my case).
          Do you know how to get around this?
          To test my theory, when I am connected to my lan from outside via VPN (also served from RasPi) it works fine also. seems definitely to be a problem with trying to reach the internal lan from outside with the get request.

          Thanks in advance if you can assist, I can’t find an answer by searching online

          Cheers
          John

          • Hi again Dan,
            I have 1 solution, but maybe it’s not very clever.
            I simply changed the LAN address in the GET request to the www address of my router (where the Raspi and Arduino are) and added port 81 to the address. I then changed the Arduino ethernet config to port 81 and added port forward rule in my router for port 81 —> Arduino.
            So now the normal HTTP request (port 80) goes to the RasPi web server and XML to the Arduino from anywhere.
            I will leave it up (connected to nothing in real life) at vk5oi.gotgeeks.com
            Have a look, but bear in mind I’m just learning HTML, CSS, Java, Linux and Arduino and am terible at all of them.

            John

  73. Hi
    I have been trying to adapt your web page to display data from a solar hot water system I built with ardunio. It is working except I am having problems trying to format the data to make it more readable.

    I am sending three values ( days high temperature , hour, minutes)
    and I want it to display in the second box (switches) as
    Todays High: 25.25 at 23:16
    I tried modifying a line like below
    Todays Low: …
    This is what I get…. correct, but not very readable.
    Todays Low: 25.252316 > at < … : …

    So tried this
    Todays High: … ( hard to tell here, but there is a space before the second two “switches”)
    This one produces
    Todays Low: 25.252316
    Can you tell me how to get the “at” and “:” into the displayed text.
    I clearly don’t understand how to do it and haven’t found anything on the web to describe how to do it. Also, what does the >…< do in the class function . I am guessing that it puts in the decimal point in a floating value, but just guessing .
    Thanks for your help..
    Mike

    • Hi again
      I just posted a question and noticed that the examples . I put in the question got striped out. So here they are without the greater or less than characters.
      So hopefully they will show.
      p Todays High: span class=”switches” at “switches”: “switches” … /span /p
      and
      p Todays High: span class=”switches” … /span _at_
      span class=”switches” … /span :
      span class=”switches” … /span
      /p

  74. Greetings,
    first of I would like to thank you for your tutorial. I did all the examples and it all are working fine. It helps me a lot to continue my final project.
    But the problem is when I switch On/Off the LED using button or check box, it takes time to On and Off (approximately 30-40 seconds), I dont know why?
    can you help me to solve this problem.

    thank you very much

  75. This is the only tutorial worh looking at.The code is FULLY EXPLAINED.
    I am new to web sever,my aim is to use the web io ,as the front end for my home automation.THE code worked first time and has not crashed yet,my problem is 1, how to change the switches to momentary(a 1 second pulse),and 2 one of the boxes on the web page to show serial data from the arduino in real-ish time (updated every 2 second will be fine) ,i cannot see any where on the web where this is shown clearly.I have on order a book that should help.Thanks in advance and keep up the GOOD WORK.

  76. I would like to add images to the web page in Part 14, so I looked at Part 11 for guidance. There are two differences I noticed. One is that in Part 11, it uses if/else statements in the sections where the HTTP requests are made, but in Part 14 it uses if/else if statements. The other is that in Part 11, the connection is closed after each HTTP request, but in Part 14 the connection is kept alive. Can you tell me which should be used if I want to add images to Part 14?

    Thank you.

    • Hi Dan
      The code in Part 11 will respond to a browser request for an image. Part 14 will not display images. Each part of the tutorial is kept as simple as possible for learning purposes, so may not contain all functionality of previous parts.

      You will really need to follow the tutorial carefully so that you understand how the code works. You can then combine the parts that you want in your own projects.

        • Hi Dan,
          FYI I just ran into the same problem and as a quick and dirty hack I wrote another html site to display my page hosted elswhere (with images, css, fancy) and load the data from the Arduino in via .
          But I’d be glad to see someone sharing working examples of part 14 e.g. combined with images.
          Cheers
          B

  77. Hi Dan,

    Recently I moved away from Picaxe due to limitations. When I found out about Arduino a whole new world opened up for me. I am working on a aquaponics system which will have 30 input sensors and 10 outputs. It is not too difficult to write up a program how to control all these I/O’s but I had no idea how to make this information available on the net. Thanks to your excellent tutorials I will be able to write something up.
    One request:
    I have been in Antarctica for more then a year now and we have very limited internet connection. It takes ages for a webpage to load. Do you have these tutorials available in a PDF format? I could then download it overnight and wouldn’t be dependent on the net when I want to use it.
    It must have been a big job to write this all up. You’ve done an excellent job and I really appreciate you sharing this information with us!
    Best greetings from Mawson, Antarctica.
    Luc

  78. Hi,

    First I’d like to congratulate you for the amazing work. The tutorial really helped me. I’m currently working in a project that controls the lights of my house, shows the ambient temperature, the state of the doors (if it is open or not), shows the local weather information and send a message to a display all by a website. I’m using SD card/Ajax solution to send the updated information to the site, as in the Part 16, but the LED checkbox code is not working in my sketch. Can you help me with that? If you wish I can send you the index.htm file I’m using and the Sketch so you can take a look, or I can post here, which you prefer?

    Thanks in advance

    Best Regards

  79. The code in Part 4 works just fine on a UNO, but when I try to run it on a DUE it hangs ( initialises SD card OK, but the ethernet server is ‘deaf’ and never replies to client requests ).

    By messing with the code, I can read a file from the SD card into an array from within the ‘setup’ block, so I know the card is OK and chip select does what it should … then I can send the array back to the client from inside the ‘loop’ routine ( code inserted in place of the direct SD card access routine ) … and that works fine.

    Any ideas ?

  80. Can any help me with my project ,i am using the ajax sd (16)sketch.
    I would like to know if there is any way to use the serial pins on the arduino to print text directly to page on the web server ,if not can i use the mega board to do so.Some idea of coding will be very helpful.THANKS in advance
    ps i am using a leonardo board

  81. Hi, thank you very much for great tutorial. Im complete newbie to arduino and I went through all the examples and it taught me a lot. I know you did this already 10 months back, but I think people can use is for several years.

    Maybe if you could add some comment/remark in the tutorial on the RAM issues on UNO that occur when people modify your code and add stuff into it, that would be great.

    I have one question, throughout the tutorial you use two functions for looking up strings in the html request: HTTP_req.indexOf and yours “home” made one. Which one is better to use and why? Thanks again

    • Hi kingbean
      Thanks for your feedback.
      The HTTP_req.indexOf uses the String object and this is the one that uses up a lot of memory but makes the code look simpler. The other method is used to reduce the amount of memory (RAM) used.

  82. Hi, first of all thank you very much for these tutorials, from which I learned a lot about arduino in conjunction with the ethernet/sd shield.
    After I went through all tutorials, I am now wonderung why in part 15 your video the needle of the gauge shows exactly the value of the analog pin in the text above the gauge. When I turn my potentiometer which is connected as you described, the text value shows 930 (also the text in the gauge), but the needle is at 1000. The higher it goes the more the difference between the needle and the text is.

    After I went through all the descriptions and wiki from mikhus canvas i still couln’t figure out how you switched the gauge text to digital font without using the font subdirectory or its files in the index.htm.

    Thank you very much for helping me out in this matter.

    Nelson

    • I figured it out, why the gauge-needle does not correspond to the analog value. The data-major-ticks have to be linear and the whole gauge has to be 100%. So I switched the major ticks to the following values:

      data-major-ticks=”0 100 200 300 400 500 600 700 800 900 1000 1100″

      I also switched the data-highlights to see, that values over 1023 can not be displayed. Here’s my canvas html code:

      Thanks again for this perfect tutorial.

      Nelson

      • sorry, canvas code did not appear. I try it again:

        data-type=”canv-gauge”
        data-min-value=”0″
        data-max-value=”1100″
        data-major-ticks=”0 100 200 300 400 500 600 700 800 900 1000 1100″
        data-value=”100″
        data-colors-needle=”#f00 #00f”
        data-highlights=”0 256 #eee, 256 512 #ccc, 512 768 #aaa, 768 1023 #FE9A2E, 1023 1100 #FF0000″
        data-onready=”setInterval( function() { Gauge.Collection.get(‘an_gauge_1’).setValue(data_val);}, 200);”

  83. Hi an thank’s a lot for this tutorial,

    I just have really big problems with the part 4 an part 10. So in the former parts I can connect to my arduino Uno without any problems, but if I try to serve a website from the sd card I didn’t get any connection, but also no failure from my webbrowser.
    I just uploaded the code from the examples an modified the ip adress. I also tried modifiing the mac adress – but I never could serve to the webpage.

    So, I’m sorry about my own question, I think I just missed a small change in the code. But I didn’t see any solution for my problem.

  84. Thanks- these helped me get my mind round the whole Arduino and Ethernet thing.

    Part 5 becomes tricky when you expand it to more than one led, say A and B. Let’s say you start up and turn A on- so far so good. You can toggle A off. then toggle B on and off, no problems.

    Tricky part comes when you turn A on and then turn B on: the GET for turning B on includes A and B in the url. So when you look for A, as usual, you find it and turn A off, even tho it was not unclicked and should stay on.

    It’s coming down to checking where it is in the GET, as you said, and if it’s at the top so to speak, the led must be on, even if it was already.

    But it’s more complicated than that, becasue of when it puts the led in the Referred part of the GET, and I’m still investigating the combinations.

    Solution to follow, and I’m open to hearing from others.

  85. Part 10: Linking pages…. Improvements.

    I have code that does both of the improvements that the author suggests.

    1) The page name (in fact, any resource name like a jpg) is extracted from the GET and so the sketch doesn’t need that info hard-coded

    2) If a page is not found, I issue a soft-404 FNF. (That’s a code 200 OK with an error page- the browser doesn’t actually know it’s an error)

    A further improvement is:

    3) Added an icon to the browser tab of each page (a “favicon”)

    Anybody want the code for all that, email jim [dot] brownza [at] gmail [dot] com

  86. Must add though, that my method of parsing the file name from the GET uses the String approach. I redid the author’s work, which used the char array approach. String is easier (to me anyway, more user-friendly coding) but it does as mentioned in an earlier post, use more memory.

  87. Just curious to if i could see an example or get advice on something like part 16 but for 8 outputs with buttons only no checkboxes. I can get all the inputs i need working just having issues with output status and control with buttons. when trying to copy/paste and change as needed to get more than 4.

    • Hi Damien
      Once you understand how the code works from the tutorial you should be able to modify it to your needs. I have seen that other people have also had problems increasing the number of I/O and wanted to add a tutorial for this. At the moment I barely have time to answer comments, but will add a tutorial when possible – it won’t be soon though, unfortunately.

      • I got it figured out I deleted the settled function callout in middle of code. thx for the tutorial I just started over then saw my glitch.

  88. Many thanks for a wonderful series, I have learned heaps, had no knowledge of AJAX before. I am constructing an engine management system for large power boat, analog gauges are perfect for tacho’s, figured out how to add second gauge by duplicating and renaming canvas section of code in body of html, works great. Great work.

    • Hi Bruce
      Thanks for your feedback and I am glad to hear that you found the tutorial useful. I wish you all the best with your project.

  89. Hi, I’d like to congratulate you about the great tutorials keep it up .
    I’m working on the SD Card Web Server I/O tutorial number (16), i want to make a modification so that i can use 4 push buttons rather than tow , i have done changes in the code to suit the two added buttons . i have increased boolean LED_state[6] = {0}; // stores the states of the LEDs and there fore the corresponding parameters so that it works . But the problems is when the web page loads and i click on any button it does not change its state from on to off but when i measure the volt it toggles from 0volt to 5 volt but it does not show in the button in web page . please i need it urgently to know the cause thank u in advance

    • You need to add changes in arduino sketch:
      void SetLed and void XML_response(EthernetClient cl)
      and in the index file: GetButton, javascrip….

  90. Hi,
    Base on your arduino web server I was able to modify and finish my home security project. I have 6 PIRs and 4 switches, I can see the states of all and I can control (ON/OFF) from the browser. Added more buttons for some light, for open my home door and insert password access for server. I manage to add in the sketch pushnotification for all states, received directly to my android.

    So, I want more. I want to connect arduino with my android phone. During my research I found NetIO, an app for my android. With NetIO you can make your own app with buttons,switches, readings and sliders, that can do different commands. The problem is that NetIO need a connection with arduino. I found some examples and use it and all I was able to do is change a state of a led using http (….host../ajax_inputs&LED2=1) but I dont receive the state reading back (when I change state from app, it change in the browser too….but when I change state from browser, it doesn’t change in the app ).
    I want to make a connection with NetIO but keep the ajax server connection with browser too.

    Anybody have done this with NetIO, or some example of anything will be very welcome.

    Thank you for your time.

  91. Hi Thank you very much for your tutorial they are very useful, I am using the example 16 but my layout is a little differet I am using a ENC28J60 module and an external SD card module with the library UIPEthernet and SDfat the code works ok but after a couple of loops It crashes do you have any idea of what could it be ?

    Regards

    Max

  92. I modified the input/output example using ajax and xml on an SD cards with success but would like to use ajax to accept a text input to change some temperature setting. I have been scrubbing the web with no luck. Ideas?

    • Hi Mark
      If you want to send temperature settings to the Arduino from the web page, you need to generate a GET request that contains the temperature settings.
      In this part of the tutorial: http://startingelectronics.com/tutorials/arduino/ethernet-shield-web-server-tutorial/SD-card-IO/
      the LEDs are controlled using a GET request.
      You will need to create a form using the HTML <form> element with a Text input so that you can type the temperature settings in and then send them using GET in the same way that the LED states are sent in the above part of the tutorial.

      • Thanks. I am new to this. Could you post an example of how to create the form, pass the variable using ajax and manipulate in the arduino IDE?

          • finally i solved it

            if (StrContains(HTTP_req, “GET /”)) {
            GET = “”;
            while(client.available()){
            c = client.read();
            GET += c;
            }

            // send rest of HTTP header
            client.println(“Content-Type: text/xml”);
            client.println(“Connection: keep-alive”);
            client.println();
            lights();
            StartHourplusminus();
            Startminutesplusminus();
            value();

            // send XML file containing input states
            XML_response(client);
            }

            int value(){
            char *value = HTTP_req;
            String val =value;

            String cmdname = String(String(val.charAt(16)));

            //command
            if(cmdname ==”h”){
            String cmdname1 = String(String(val.charAt(17))+String(val.charAt(18)));

            Serial.print(cmdname1);
            val1 =cmdname1.toInt();
            }
            }

  93. Thanks for this great and very useful tutorial!
    I am using a modified version of the last example for my own project and it works well!
    I was wondering how to implement conditionals between sensor readings and button-control. E.g. the user can only switch on the LED from the web-interface when the switch is turned off, or an analog value is < x.
    I know how to write this in the Arduino but how can implement this into the HTML interface? (E.g. greying out a button saying "Function not available" instead of LED on/LED off.
    Thanks!!!

    • Hi birgit
      You can get the Arduino to modify the web page that it hosts to reflect the button state. Like this for example:
      <button type=”button” disabled>LED</button>
      will show the button disabled. Just get the Arduino to modify this markup by removing “disabled” to show the button enabled again.
      It is also possible to move the logic into JavaScript.

  94. This is one of the best Arduino tutorial I have come across. Information is well presented and shows what can be done, Even though it just scratches the surface. It will save the the average dabbler a lot time and frustration in setting up a very basic but functional web interface.

    Thanks
    James

  95. Hello,
    many thanks for this tutorial. It helped a lot for my first real Arduino Projekt. I want to build a webserver located on a sd-card, as described in part 4. I built to buttons in the index.htm. Unfortunately there is something wrong wit the client response. If I log the character ‘c’ (see code) everything is fine, but it seemed to me that the string ‘HTTP_req’ is always empty, so I cannot handle the client response.
    <<<
    #include
    #include // Netzwerk-Bibliothek
    #include

    byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xFF, 0xA1 }; // MAC Adresse von der Shieldrückseite
    byte ip[] = {192,168,1,177}; // IP-Adresse
    byte gateway[] = { 192, 168, 178, 1 }; // Gateway
    byte subnet[] = { 255, 255, 255, 0 };

    EthernetServer server(80);
    String HTTP_req;

    int led = 2;

    File webFile;

    void setup()
    {
    Ethernet.begin(mac, ip); // initialize Ethernet device
    server.begin(); // start to listen for clients
    Serial.begin(9600); // for debugging

    pinMode(led, OUTPUT); // LED output
    // 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.”);
    }

    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
    HTTP_req = HTTP_req+c;

    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) {
    // 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
    webFile = SD.open(“index.htm”); // open web page file
    if (webFile) {
    while(webFile.available()) {
    client.write(webFile.read()); // send web page to client
    }
    webFile.close();
    }

    // An dieser Stelle wird die Abfrage gemacht:

    if(HTTP_req.indexOf(“ob=Hoch”) > -1){
    digitalWrite(led, HIGH);
    }
    if(HTTP_req.indexOf(“ob=Stop”) > -1){
    digitalWrite(led, LOW);
    }
    HTTP_req= “”; // finished with request, empty string
    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)
    }

    >>>

    Thanks you very much for your help.

    Best regards Johannes

  96. I can’t make it together …
    My final plan was to make it like the end of the tutorial, read analog + use button to change value of something in the screen, like part 7 and part 9 at the same time, but i could not figure how to do it.
    Why can’t we have acces to the .ino of the very last page 🙁

    • Hi Synless
      All the code is there. Are you talking about part 16? If so, look under the “Source Code” heading and you will find a zipped file that contains the code.

      • Excuse me, the amouth of thing in your tutorial are so huge, i didn’t read them all.
        But now this is done and day have passed, i managed to do very nice thing with your tutorial.
        I didn’t ever looked for your zipped file 😀

        Thx again.

  97. Hi i am using the ajax switches and and analogue inputs. My main problem is her to dd some maths so i can use tmp36 temperature sensors ,the conversion will not go after analogue_value as its not a function. any help with
    this would be appreciated from all using this site.

  98. Hello, thanks for this magnificent site, i found here a lot of interesting info.
    I tell you my problem, i try to add an image into the web page of the example Part 16 SD CARD WEB SERVER , but i can’t show it when i charge the page, i try also to merge some pieces of the example Part 11 but after the webserver will not update the ajax values…
    How i can do this without problems?
    Many thanks to all! 😉

  99. Hi! Thanks for the sketch and tutorial.

    I am a newbie with arduino and would like to know how i can add pushbutton switch to pin 2 to control LED3 (control via web interface (software) and also external switch (hardware) ?

    I am testing with this but if the web page is close i cannot control LED 3 with buttonswitch to pin 2 but i can with web page open.

    Thanks if you have a solution for me !
    ————————————————————————————————-/*————————————————————–
    Program: eth_websrv_SD_Ajax_in_out

    Description: Arduino web server that displays 4 analog inputs,
    the state of 3 switches and controls 4 outputs,
    2 using checkboxes and 2 using buttons.
    The web page is stored on the micro SD card.

    Hardware: Arduino Uno and official Arduino Ethernet
    shield. Should work with other Arduinos and
    compatible Ethernet shields.
    2Gb micro SD card formatted FAT16.
    A2 to A4 analog inputs, pins 2, 3 and 5 for
    the switches, pins 6 to 9 as outputs (LEDs).

    Software: Developed using Arduino 1.0.5 software
    Should be compatible with Arduino 1.0 +
    SD card contains web page called index.htm

    References: – WebServer example by David A. Mellis and
    modified by Tom Igoe
    – SD card examples by David A. Mellis and
    Tom Igoe
    – Ethernet library documentation:
    http://arduino.cc/en/Reference/Ethernet
    – SD Card library documentation:
    http://arduino.cc/en/Reference/SD

    Date: 4 April 2013
    Modified: 19 June 2013
    – removed use of the String class

    Author: W.A. Smith, http://startingelectronics.com
    ————————————————————–*/

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

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // MAC address from Ethernet shield sticker under board
    byte gateway[] = { 192, 168, 0, 1 }; // the router’s gateway address
    byte subnet[] = { 255, 255, 0, 0 }; // the subnet
    IPAddress ip(192, 168, 0, 10); // IP address, may need to change depending on network
    EthernetServer server(80); // create a server at port 80
    File webFile; // the web page file on the SD card
    char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
    char req_index = 0; // index into HTTP_req buffer
    boolean LED_state[4] = {0}; // stores the states of the LEDs

    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.”);
    // switches on pins 2, 3 and 5
    pinMode(2, INPUT);
    pinMode(3, INPUT);
    pinMode(5, INPUT);
    // LEDs
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);

    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
    // limit the size of the stored received HTTP request
    // 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++;
    }
    // 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");
    // remainder of header follows below, depending on if
    // web page or XML page is requested
    // Ajax request – send XML file
    if (StrContains(HTTP_req, "ajax_inputs")) {
    // send rest of HTTP header
    client.println("Content-Type: text/xml");
    client.println("Connection: keep-alive");
    client.println();
    SetLEDs();
    // send XML file containing input states
    XML_response(client);
    }
    else { // web page request
    // send rest of HTTP header
    client.println("Content-Type: text/html");
    client.println("Connection: keep-alive");
    client.println();
    // send web page
    webFile = SD.open("index.htm"); // open web page file
    if (webFile) {
    while(webFile.available()) {
    client.write(webFile.read()); // send web page to client
    }
    webFile.close();
    }
    }
    // display received HTTP request on serial port
    Serial.print(HTTP_req);
    // 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)
    }

    // checks if received HTTP request is switching on/off LEDs
    // also saves the state of the LEDs
    void SetLEDs(void)
    {
    // LED 1 (pin 6)
    if (StrContains(HTTP_req, "LED1=1")) {
    LED_state[0] = 1; // save LED state
    digitalWrite(6, HIGH);
    }
    else if (StrContains(HTTP_req, "LED1=0")) {
    LED_state[0] = 0; // save LED state
    digitalWrite(6, LOW);
    }
    // LED 2 (pin 7)
    if (StrContains(HTTP_req, "LED2=1")) {
    LED_state[1] = 1; // save LED state
    digitalWrite(7, HIGH);
    }
    else if (StrContains(HTTP_req, "LED2=0")) {
    LED_state[1] = 0; // save LED state
    digitalWrite(7, LOW);
    }
    // LED 3 (pin 8)
    if (StrContains(HTTP_req, "LED3=1")) {
    LED_state[2] = 1; // save LED state
    digitalWrite(8, HIGH);
    }
    else if (StrContains(HTTP_req, "LED3=0")) {
    LED_state[2] = 0; // save LED state
    digitalWrite(8, LOW);
    }
    // LED 4 (pin 9)
    if (StrContains(HTTP_req, "LED4=1")) {
    LED_state[3] = 1; // save LED state
    digitalWrite(9, HIGH);
    }
    else if (StrContains(HTTP_req, "LED4=0")) {
    LED_state[3] = 0; // save LED state
    digitalWrite(9, LOW);
    }
    }

    // send the XML file with analog values, switch status
    // and LED status
    void XML_response(EthernetClient cl)
    {
    int analog_val; // stores value read from analog inputs
    int count; // used by 'for' loops

    // variables will change:

    int lastButtonState;
    // initialize the pushbutton pin as an input:
    // pinMode(buttonPin, INPUT);
    // constants won't change. They're used here to
    // set pin numbers:
    const int buttonPin = 2; // the number of the pushbutton pin
    int buttonState;
    // read the state of the pushbutton value:
    buttonState = digitalRead(buttonPin);

    cl.print("”);
    cl.print(“”);
    // read analog inputs
    for (count = 2; count <= 5; count++) { // A2 to A5
    analog_val = analogRead(count);
    cl.print("”);
    cl.print(analog_val);
    cl.println(“”);
    }

    // read switches

    // check if the pushbutton is pressed.
    // if it is, the buttonState is HIGH:
    if (buttonState != lastButtonState && digitalRead(8) == HIGH) {
    digitalWrite(8, LOW);
    LED_state[2] = 0; // save LED state
    }
    else if (buttonState != lastButtonState && digitalRead(8) == LOW) {
    digitalWrite(8, HIGH);
    LED_state[2] = 1; // save LED state
    }

    lastButtonState = buttonState;

    // checkbox LED states
    // LED1
    cl.print(“”);
    if (LED_state[0]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }
    cl.println(“”);
    // LED2
    cl.print(“”);
    if (LED_state[1]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }
    cl.println(“”);
    // button LED states
    // LED3
    cl.print(“”);
    if (LED_state[2]) {
    cl.print(“on”);
    }
    else {
    cl.print(“off”);
    }
    cl.println(“”);
    // LED4
    cl.print(“”);
    if (LED_state[3]) {
    cl.print(“on”);
    }
    else {
    cl.print(“off”);
    }
    cl.println(“”);

    cl.print(“”);
    }

    // sets every element of str to 0 (clears array)
    void StrClear(char *str, char length)
    {
    for (int i = 0; i len) {
    return 0;
    }
    while (index < len) {
    if (str[index] == sfind[found]) {
    found++;
    if (strlen(sfind) == found) {
    return 1;
    }
    }
    else {
    found = 0;
    }
    index++;
    }

    return 0;
    }

  100. First thank you for this set of tutorials. They are nicely progressive and pedagogical.

    I was trying to implement part 5, the LED server with the checkbox. I am not sure why it is said that the LED state and the check could be out of sync: if we look at pseudo the code we either have
    {turn on led; mark box checked) or (turn off led; mark box unchecked} so, imho check mark and led are necessarily in phase as long as the page sent does make it to the browser.

    My concern is that i could only manage to have this work reliably in my home network. When i use my chrome/phone (yes with a well configured dyn client and port forwarding) oftentimes, the request from the phone includes no LED2 string, nor in the get neither in the referer. The exact symptom is that it works nicely, and then get stuck with the led on and the box checked (more precisely, on every click the check mark get cleared by the browser then set again with the page arrival). Thereafter, no way to recover. I’d vary much appreciate any help on this small program because it seem to me that this requires minimal knowledge yet allowing one set and test things at the server’s

    Thanks in advance for your time

  101. Thank you very much for your tutorials! They really help me a lot in my final year project! But when I display analog value on gauge, the webpage opens very slowly. I don’t know why? Could you help me? Many thanks!

    • The web page may take some time to load initially because the gauge code makes the page fairly big for the Arduino to send. Once loaded, there should be no problems.

  102. Hi. This tutorials are very good. I learn a lot. I have one question.
    I’m playing with part 16. SD Card Web Server I/O.
    But now i would like to add some pictures on web server.
    I know that i have to put in index.htm, but what do i have to put in arduino code. I try to add some lines from Part 11….but i still can’t get it work. Can please someone help me.

    Thank you very much

  103. Thank You!!

    I have been searching for this type of detail for days. You have shown me how to proceed with my project.
    My project is to use the eithernet control for a real time remote control for a ground based vehicle. I plan to include on the browser controls as well as statuses from the vehicle. A display in a frame of the IP camera mounted on it will allow FPV (First Person Video).
    I am aware that the “Real Time” part is going to be a challenge (fun) but why not? I am eager for the game pad browser API to become more stable and hope to include that option as well in the future. Again Thank You for your time on creating these excellent tutorials, They have given me the direction I was lacking.

    Mike

  104. great stuff but when I try to add a 2nd gauge it reads the analog input from the first gauge a2 instead of a3 where do i change this please.

    • Hi Jeff
      You need to send the second analog value to the web page in response to the Ajax request. The function XML_response( ) in the Arduino code shows how the first analog value is sent. You will also need to modify the web page Javascript to handle the new value that is being received. If you follow the tutorial carefully, you will find all the information necessary to understand how it works. You will then be able to make the modifications.

  105. usually these thing I figure out but I do not see where I can feed analog value A3 into gauge an_gauge_2 in the .js file.
    thank you!

    • Hi Jeff
      I will need some time to look at the code. Probably try to answer everyone’s questions on the weekend.

  106. In Part 15, the Gauge,

    You are doing some modification to the gauge script in the HTML, could you explain this?

    Also the Script is relying on the font sever from the smart-ip.net website, i have been trying to serve this locally from the SD-card on the shield, but with no luck, any ideas how to do this?

  107. Wow! the is easily the best tutorial I have come across. I have been trying to get my head around this for ages, but there were too many new concepts all at once. Arduino, HTML, Java, Ajax etc, but you somehow lay it out so it fits together.
    I have added a gauge to section 16, and it works great. I also am having trouble with the second (and third) gauge, like Jeff above, but I am sure I’ll get it. Just need to understand better what I am doing.
    Thanks a million, brilliant stuff.

  108. Hello! I’m really enjoying this tutorial. very nice. In Part 7, I recorded the index.html in SD, but when I open it in Chrome the buttons do not appear. The java is active. Thank you.

  109. Why the Server and Client are on the same Lan work perpectly, while when between them the is Internet cloud I can’ t see the web page of Ardino Server.

    Thank you

    Flavio

  110. Hello,

    I am learning part 5 to control robot by web server. I replace switching LED by enable/disable motor rotation. But I only on/off about 3~4 times and then, ethernet shield is not working anymore. I have to reset it but after 3~4 times. this issue happens again. Could you help me fix it?
    Thank you so much.

  111. First of all i would like to say thanks for a great tuition it help me a lot but i am having a problem in one section of the code where the analog float value causing problem in displaying the web page eg. cl.print(float value) which causes problem if i define variable in integer then it is ok. i am attaching the code below.

    should i convert float value to string if it is yes then how??

    /*————————————————————–
    Program: eth_websrv_SD_Ajax_in_out

    Description: Arduino web server that displays 4 analog inputs,
    the state of 3 switches and controls 4 outputs,
    2 using checkboxes and 2 using buttons.
    The web page is stored on the micro SD card.

    Hardware: Arduino Uno and official Arduino Ethernet
    shield. Should work with other Arduinos and
    compatible Ethernet shields.
    2Gb micro SD card formatted FAT16.
    A2 to A4 analog inputs, pins 2, 3 and 5 for
    the switches, pins 6 to 9 as outputs (LEDs).

    Software: Developed using Arduino 1.0.5 software
    Should be compatible with Arduino 1.0 +
    SD card contains web page called index.htm

    References: – WebServer example by David A. Mellis and
    modified by Tom Igoe
    – SD card examples by David A. Mellis and
    Tom Igoe
    – Ethernet library documentation:
    http://arduino.cc/en/Reference/Ethernet
    – SD Card library documentation:
    http://arduino.cc/en/Reference/SD

    Date: 4 April 2013
    Modified: 19 June 2013
    – removed use of the String class

    Author: W.A. Smith, http://startingelectronics.com
    ————————————————————–*/

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

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //assign arduino mac address
    byte ip[] = { 192, 168, 0, 177 }; // ip in lan assigned to arduino
    byte gateway[] = { 172, 18, 5, 1 }; // internet access via router
    byte subnet[] = { 255, 255, 255, 0 }; // IP address, may need to change depending on network
    EthernetServer server(80); // create a server at port 80
    File webFile; // the web page file on the SD card
    char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
    char req_index = 0; // index into HTTP_req buffer
    boolean LED_state[7] = {0}; // stores the states of the LEDs

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

    // 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.”);
    // switches on pins 2, 3 and 5
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(5, OUTPUT);
    // LEDs
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);

    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
    // limit the size of the stored received HTTP request
    // 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++;
    }
    // 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");
    // remainder of header follows below, depending on if
    // web page or XML page is requested
    // Ajax request – send XML file
    if (StrContains(HTTP_req, "ajax_inputs")) {
    // send rest of HTTP header
    client.println("Content-Type: text/xml");
    client.println("Connection: keep-alive");
    client.println();
    SetLEDs();
    // send XML file containing input states
    XML_response(client);
    }
    else { // web page request
    // send rest of HTTP header
    client.println("Content-Type: text/html");
    client.println("Connection: keep-alive");
    client.println();
    // send web page
    webFile = SD.open("index.htm"); // open web page file
    if (webFile) {
    while(webFile.available()) {
    client.write(webFile.read()); // send web page to client
    }
    webFile.close();
    }
    }
    // display received HTTP request on serial port
    Serial.print(HTTP_req);
    // 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)
    }

    // checks if received HTTP request is switching on/off LEDs
    // also saves the state of the LEDs
    void SetLEDs(void)
    {
    // LED 1 (pin 2)
    if (StrContains(HTTP_req, "LED1=1")) {
    LED_state[0] = 1; // save LED state
    digitalWrite(2, HIGH);
    }
    else if (StrContains(HTTP_req, "LED1=0")) {
    LED_state[0] = 0; // save LED state
    digitalWrite(2, LOW);
    }
    // LED 2 (pin 3)
    if (StrContains(HTTP_req, "LED2=1")) {
    LED_state[1] = 1; // save LED state
    digitalWrite(3, HIGH);
    }
    else if (StrContains(HTTP_req, "LED2=0")) {
    LED_state[1] = 0; // save LED state
    digitalWrite(3, LOW);
    }
    // LED 3 (pin 5)
    if (StrContains(HTTP_req, "LED3=1")) {
    LED_state[2] = 1; // save LED state
    digitalWrite(5, HIGH);
    }
    else if (StrContains(HTTP_req, "LED3=0")) {
    LED_state[2] = 0; // save LED state
    digitalWrite(5, LOW);
    }
    // LED 4 (pin 6)
    if (StrContains(HTTP_req, "LED4=1")) {
    LED_state[3] = 1; // save LED state
    digitalWrite(6, HIGH);
    }
    else if (StrContains(HTTP_req, "LED4=0")) {
    LED_state[3] = 0; // save LED state
    digitalWrite(6, LOW);
    }

    //changes done from here add extra pin
    // LED 5 (pin 7)
    if (StrContains(HTTP_req, "LED5=1")) {
    LED_state[4] = 1; // save LED state
    digitalWrite(7, HIGH);
    }
    else if (StrContains(HTTP_req, "LED5=0")) {
    LED_state[4] = 0; // save LED state
    digitalWrite(7, LOW);
    }
    // LED 6 (pin 8)
    if (StrContains(HTTP_req, "LED6=1")) {
    LED_state[5] = 1; // save LED state
    digitalWrite(8, HIGH);
    }
    else if (StrContains(HTTP_req, "LED6=0")) {
    LED_state[5] = 0; // save LED state
    digitalWrite(8, LOW);
    }
    // LED 7(pin 9)
    if (StrContains(HTTP_req, "LED7=1")) {
    LED_state[6] = 1; // save LED state
    digitalWrite(9, HIGH);
    }
    else if (StrContains(HTTP_req, "LED7=0")) {
    LED_state[6] = 0; // save LED state
    digitalWrite(9, LOW);
    }

    }

    // send the XML file with analog values, switch status
    // and LED status
    void XML_response(EthernetClient cl)
    {
    int analog_val0; // stores value read from analog inputs
    int analog_val1; // stores value read from analog inputs
    int analog_val2; // stores value read from analog inputs
    int analog_val3; // stores value read from analog inputs

    int count; // used by 'for' loops
    int sw_arr[] = {2, 3, 5, 6, 7, 8, 9}; // pins interfaced to switches

    cl.print("”);
    cl.print(“”);
    // read analog inputs
    for(count = 0;count <= 5; count++)
    {// A2 to A5

    analog_val0 = analogRead((count)= 2);

    float tempC = analog_val0/ 9.31;
    cl.print("”);
    cl.print(tempC); //float value causing problem
    cl.println(“”);

    analog_val1 = analogRead((count)=3);
    cl.print(“”);
    cl.print(analog_val1);
    cl.println(“”);

    analog_val2 = analogRead((count)=4);
    cl.print(“”);
    cl.print(analog_val2);
    cl.println(“”);

    analog_val3 = analogRead((count)=5);
    cl.print(“”);
    cl.print(analog_val3);
    cl.println(“”);

    }
    // read switches
    for (count = 0; count < 6; count++) {
    cl.print("”);
    if (digitalRead(sw_arr[count])) {
    cl.print(“ON”);
    }
    else {
    cl.print(“OFF”);
    }
    cl.println(“”);
    }
    // checkbox LED states
    // LED1
    cl.print(“”);
    if (LED_state[0]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }
    cl.println(“”);

    // LED2
    cl.print(“”);
    if (LED_state[1]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }
    cl.println(“”);
    // button LED states
    // LED3

    cl.print(“”);
    if (LED_state[2]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }
    cl.println(“”);

    // LED4
    cl.print(“”);
    if (LED_state[3]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }
    cl.println(“”);

    // LED5
    // chaange in xml file
    cl.print(“”);
    if (LED_state[4]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }
    cl.println(“”);
    // chaange in xml file
    // LED6
    cl.print(“”);
    if (LED_state[5]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }
    cl.println(“”);

    // LED7
    cl.print(“”);
    if (LED_state[6]) {
    cl.print(“checked”);
    }
    else {
    cl.print(“unchecked”);
    }

    cl.print(“”);

    cl.print(“”);
    }

    // sets every element of str to 0 (clears array)
    void StrClear(char *str, char length)
    {
    for (int i = 0; i len) {
    return 0;
    }
    while (index < len) {
    if (str[index] == sfind[found]) {
    found++;
    if (strlen(sfind) == found) {
    return 1;
    }
    }
    else {
    found = 0;
    }
    index++;
    }

    return 0;
    }

  112. Hello,

    I use this tutorial to do a remote IP camera.
    Thanks to author of this smart tutorial!
    You can see my project on https://github.com/briks/ipcam
    I’ve one question, as a total newby in html code, the only way I found to reload a picture from a arduino web server using this tutorial is to relaod the entire page with a refresh command, whe user click the button I call:
    function showImg()
    {
    window.location.reload();
    }
    I don’t found a smarter way to process this! If you have an idea 🙂

  113. Is the following possible?

    Assume that there is a virtual button in HTML and one needs to distinguish between a tap and a hold.

    So, let’s say you tap a button on the webpage and a physical LED blinks once.

    If you hold that button on the webpage, the physical LED keeps blinking until released.

  114. GREAT TUTORIAL! Really appreciate your great work!

    I’m working on a project where i want to display all the analog inputs on different gauges. The code you provided in this tutorial works, but i’ve tried to add an extra gauge in the html code by copying the gauge code and add a new line of this analog input where i change it to another analog input:

    “void XML_response(EthernetClient cl)
    {
    int analog_val;

    cl.print(“”);
    cl.print(“”);
    // read analog pin A2
    analog_val = analogRead(2);
    cl.print(“”);
    cl.print(analog_val);
    cl.print(“”);
    cl.print(“”);
    }”

    but what has to be done in the html code? I’m not quite sure what has to be edited in the second pasted gauge code in the html script. My understanding was that the code
    “data_val = this.responseXML.getElementsByTagName(‘analog’)[0].childNodes[0].nodeValue;”
    The data_val is the command that samples the analog signal, by the (‘analog’).

    What has to be changed in the pasted html code in the html file and what has to be supplied to the arduino code to make it feed the second gauge with a new analog input value?

  115. Just want to say thanks for this great tutorial, this is my second project and I am so grateful to people like you who spend time helping us.

    Thank you

  116. Thanks for a great tutorial it helped me lot but i am having problem with option button which got value to choose from 1-60 for min and and another option from 0-23 hrs and i want to select the value for the option button and then submit the value to the arduino but i am not able to get the value to arduino how to do so ,so that i can set the clock from the webpage.
    Example:
    Minute

    1
    2
    3
    ……60

    Hours

    1
    2
    3
    To …..23

    var sel = document.getElementById(“Example”);
    var value = sel.options[sel.selectedIndex].value;

    var sel = document.getElementById(“Example1”);
    var value = sel.options[sel.selectedIndex].value;

    How to send “var value” to arduino with ajax like the one you have shown in the case of buttons and check box.

  117. tutorials are really very useful,

    I came across this article “Arduino SD Card Web Server – Displaying Images”

    But I’m looking to transfer image directly from SD card to webserver. I’m was trying with ETHER_28J60 and UIPEthernet libraries with hardware ENC28J60 & Arduino Uno but no luck till now. If you can guide me on same it would be really very helpful.

    Thanks & Regards

  118. Hi, really great job with the tutorials. I would like to have my arduino as a web client so the page will not be hosted on it but for example on my pc. I found here questions about it from last year but without answer. I want to do the same as in tutorials but from the page not hosted by arduino. Can you help me with that?

    • Hi matej
      I intended to publish a tutorial on the Arduino as a web client, but have not had the time yet. I am so busy with work at the moment. Can’t make any promises when it will be done.
      Starting Electronics

  119. Like many people before me, I want to thank you for this excellent tut. I worked my way up to section 16, writing, modifying and trying to understand what you try to teach me. So far so good. I made the arduino Ajax Dial part with a gauge and that also works great. But I still can’t figure out how to insert a second (and a third) gauge and get the data from other analog pins in it. 1 gauge works fine, but when I place a second gauge next to it, I don’t get any data in both of them.
    t seems like I have the same problem as Jeff and John above here and I know you are very busy atm but If you could help us with this that would be great.

    thanks and regards,

    Ulco

    • I figured out how to get 4 gauges working.
      It may be not the the most elegant solution but since I am just starting in this, I want to share it with others who have the same problem.

      In the arduino code I just entered a few more lines to the “send XML” part:

      // send the XML file containing analog value
      void XML_response(EthernetClient cl)
      {
      int analog_vala;
      int analog_valb;
      int analog_valc;
      int analog_vald;

      cl.print(“”);
      cl.print(“”);
      // read analog pins
      analog_vala = analogRead(2);
      analog_valb = analogRead(3);
      analog_valc = analogRead(4);
      analog_vald = analogRead(5);

      cl.print(“”);
      cl.print(analog_vala);
      cl.print(“”);

      cl.print(“”);
      cl.print(analog_valb);
      cl.print(“”);

      cl.print(“”);
      cl.print(analog_valc);
      cl.print(“”);

      cl.print(“”);
      cl.print(analog_vald);
      cl.print(“”);

      cl.print(“”);
      }

      • In the HTML code, I drew all the gauges seperately:

        function GetArduinoInputs()
        {
        nocache = “&nocache=” + Math.random() * 1000000;

        var request = new XMLHttpRequest();

        request.onreadystatechange = function()
        {
        if (this.readyState == 4)
        {
        if (this.status == 200)
        {
        if (this.responseXML != null)
        {
        document.getElementById(“input3”).innerHTML =
        this.responseXML.getElementsByTagName(‘analoga’)[0].childNodes[0].nodeValue;
        data_vala = this.responseXML.getElementsByTagName(‘analoga’)[0].childNodes[0].nodeValue;

        document.getElementById(“input4”).innerHTML =
        this.responseXML.getElementsByTagName(‘analogb’)[0].childNodes[0].nodeValue;
        data_valb = this.responseXML.getElementsByTagName(‘analogb’)[0].childNodes[0].nodeValue;

        document.getElementById(“input5”).innerHTML =
        this.responseXML.getElementsByTagName(‘analogc’)[0].childNodes[0].nodeValue;
        data_valc = this.responseXML.getElementsByTagName(‘analogc’)[0].childNodes[0].nodeValue;

        document.getElementById(“input6”).innerHTML =
        this.responseXML.getElementsByTagName(‘analogd’)[0].childNodes[0].nodeValue;
        data_vald = this.responseXML.getElementsByTagName(‘analogd’)[0].childNodes[0].nodeValue;
        }

        }

        }

        }
        request.open(“GET”, “ajax_inputs” + nocache, true); request.send(null); setTimeout(‘GetArduinoInputs()’, 400);

        }

        Arduino Ajax Dial

        Analog (A2): …

        Analog (A3): …
        Analog (A4): …
        Analog (A5): …

        var gauge1 = new Gauge({
        renderTo : ‘gauge1’,
        width : 300,
        height : 300,
        maxValue : 30,
        majorTicks : [‘0′,’3′,’6′,’9′,’12’,’15’,’18’,’21’,’24’,’27’,’30’],
        glow : true,
        units : ‘graden’,
        title : ‘temperatuur’,
        strokeTicks : false,
        highlights : [{
        from : 0,
        to : 5,
        color : ‘#F62217’
        }, {
        from : 5,
        to : 10,
        color : ‘#F87217’
        }, {
        from : 10,
        to : 15,
        color : ‘#FDD017’
        }, {
        from : 15,
        to : 20,
        color : ‘#57E964’
        }, {
        from : 20,
        to : 22,
        color : ‘#FDD017’
        }, {
        from : 22,
        to : 25,
        color : ‘#F87217’
        }, {
        from : 25,
        to : 30,
        color : ‘#F62217’
        }],
        animation : {
        delay : 10,
        duration: 300,
        fn : ‘bounce’
        }
        });

        gauge1.onready = function() {
        setInterval( function() {
        gauge1.setValue(data_vala/20);
        }, 1000);
        };

        gauge1.draw();

        var gauge2 = new Gauge({
        renderTo : ‘gauge2’,
        width : 300,
        height : 300,
        maxValue : 14,
        majorTicks : [‘0′,’2′,’4′,’6′,’8′,’10’,’12’,’14’],
        glow : true,
        units : ‘pH’,
        title : ‘pH waarde’,
        strokeTicks : false,
        highlights : [{
        from : 0,
        to : 5,
        color : ‘#F62217’
        }, {
        from : 5,
        to : 5.5,
        color : ‘#F87217’
        }, {
        from : 5.5,
        to : 6,
        color : ‘#FDD017’
        }, {
        from : 6,
        to : 8,
        color : ‘#57E964’
        }, {
        from : 8,
        to : 8.5,
        color : ‘#FDD017’
        }, {
        from : 8.5,
        to : 9,
        color : ‘#F87217’
        }, {
        from : 9,
        to : 14,
        color : ‘#F62217’
        }],
        animation : {
        delay : 10,
        duration: 300,
        fn : ‘bounce’
        }
        });

        gauge2.onready = function() {
        setInterval( function() {
        gauge2.setValue(data_valb/35);
        }, 1000);
        };

        gauge2.draw();

        var gauge3 = new Gauge({
        renderTo : ‘gauge3’,
        width : 300,
        height : 300,
        maxValue : 10,
        majorTicks : [‘0′,’1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’10’],
        glow : true,
        units : ‘mg/l’,
        title : ‘DO waarde’,
        strokeTicks : false,
        highlights : [{
        from : 0,
        to : 4.5,
        color : ‘#F62217’
        }, {
        from : 4.5,
        to : 5.5,
        color : ‘#F87217’
        }, {
        from : 5.5,
        to : 6.5,
        color : ‘#FDD017’
        }, {
        from : 6.5,
        to : 10,
        color : ‘#57E964’
        }],
        animation : {
        delay : 10,
        duration: 300,
        fn : ‘bounce’
        }
        });

        gauge3.onready = function() {
        setInterval( function() {
        gauge3.setValue(data_valc/50);
        }, 1000);
        };
        gauge3.draw();

        var gauge4 = new Gauge({
        renderTo : ‘gauge4’,
        width : 300,
        height : 300,
        maxValue : 1000,
        majorTicks : [‘0′,’100′,’200′,’300′,’400′,’500′,’600′,’700′,’800′,’900′,’1000’],
        glow : true,
        units : ‘liter’,
        title : ‘water level’,
        strokeTicks : false,
        highlights : [{
        from : 0,
        to : 500,
        color : ‘#F62217’
        }, {
        from : 500,
        to : 600,
        color : ‘#F87217’
        }, {
        from : 600,
        to : 700,
        color : ‘#FDD017’
        }, {
        from : 700,
        to : 1000,
        color : ‘#57E964’
        }],
        animation : {
        delay : 10,
        duration: 300,
        fn : ‘bounce’
        }
        });

        gauge4.onready = function() {
        setInterval( function() {
        gauge4.setValue(data_vald*2);
        }, 1000);
        };

        gauge4.draw();

        Note that this is not the complete code but just the part I changed.

        I hope this was useful for some of you.

        Ulco

      • Hi Ulco
        Thanks for posting your solution, its appreciated that your put the effort in.
        I tried nearly exactly what you suggest and I still had no success.. Obviously I am doing something wrong, but now I have confidence I am on the right track.
        I will try again when work allows some time, and will maybe post the result (good or bad ) here for assistance.
        Thanks again
        John

        • Hi Ulco, and Starting Electronics
          It seems Ulco is correct, and the new tutorial by Starting Electronics is correct, and as it turns out, so was I all along.
          Mine however did not work because what I did not realise (and might help others) is that is the analogue value is outside of the min/max limits set for the gauge, then the gauge on the web page fluctuates wildly.
          Every time I tried to add another gauge, I saw this behaviour and thought my code was wrong. I tried different Arduino boards and a million different variations to the code. If I had the connected pot in an acceptable range, then I would not have seen the wild behaviour first.
          So….thanks to Ulco and others and starting electronics for persisting with your excellent help until I worked out my mistake…
          I donated a few months ago, I think I will donate again.

          • Hi John
            Thanks for your feedback and donation. Good to hear that you found the problem.
            Starting Electronics

  120. Hi! Can you help me to write an arduino program that reads the content of the message box from the webserver then display the value to arduino serial monitor? I’m following your code but it doesn’t have an example regarding a text box with a submit button.

  121. Hi, thanks for the interesting sketches, there is a lot to learn and build from.

    I did not get the SD-card-web-server running, and I do not understand how it can work. You warned against using the ethernet shield and the SD card at the same time: interference on the SPI. However, in this sketch it seems that you just do this. No disabling/enabling of the two functions, using port 4 and 10 necessary here?

    Thanks!

    • Hi gert3d
      Thanks for your feedback. I did not disable the Ethernet chip first (on pin 10) because I never had any problems with the SD-card-web-server (part 4). I actually recently ran through the whole tutorial with a new Arduino Ethernet (http://blog.startingelectronics.com/?p=811)

      What hardware are you using to run the SD-card-web-server?
      You may need to disable the Ethernet chip at the top of the setup() part of the sketch:
      // disable Ethernet chip
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);
      Please let me know if this works or not and which Arduino you are using.

      • Hi, thanks for your quick reply and interest.
        I fiddled around and found out that I got it working with the setup() as below.

        I am using Arduino Uno from SainSmart and a SD-Web server board excactly as you show in part 5.

        I looks like the order of commands and disabling the W5100 does the trick?

        void setup()
        {
        Serial.begin(9600); // for debugging

        // initialize SD card
        pinMode(10, OUTPUT); // change this to 53 on a mega
        digitalWrite(10, HIGH); // and turn off the W5100 chip!

        pinMode(4,OUTPUT);
        digitalWrite(4, LOW); // activate 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.”);
        digitalWrite(4,HIGH); // disable SD SPI

        Ethernet.begin(mac, ip, gateway, gateway, subnet); // initialize Ethernet device set up w5100
        digitalWrite(10,HIGH); // essential !
        server.begin(); // start to listen for clients
        }

  122. Hello,

    Let me first say the work you have done here has vastly helped understand of not only arduino but also html!

    With that being said I’m having a issue with my project. I would like to have multiple pages on a SD card one of the pages using AJAX to report the value of POT. I am able to have one page off the SD card using AJAX as you illustrated. But I cannot seem to be able to call the other page.
    Here is what my code looks like. I was able to get it to compile but when I go to the IP address, page one isn’t being illustrated.

    #include
    #include
    #include

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

    // MAC address from Ethernet shield sticker under board
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(10, 0, 0, 18); // 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++;
    }
    // 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: keep-alive");
    client.println();
    // Ajax request
    if (StrContains(HTTP_req, "ajax_switch")) {
    // read switch state and send appropriate paragraph text
    GetSwitchState(client);
    }
    if(StrContains(HTTP_req, "GET / ")
    || StrContains(HTTP_req, "GET /index.htm")) {
    webFile = SD.open("page1.htm"); // open web page file
    }
    else if (StrContains(HTTP_req, "GET /page2.htm")) {
    webFile = SD.open("page2.htm");
    if (webFile) {
    while(webFile.available()) {
    client.write(webFile.read()); // send web page to client
    }

    webFile.close();
    }
    }
    // display received HTTP request on serial port
    Serial.println(HTTP_req);
    // 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)
    }

    // send the state of the switch to the web browser
    void GetSwitchState(EthernetClient cl)
    {
    int analog_val;
    analog_val = analogRead(0);
    cl.print("Binocular Number: “);
    cl.print(analog_val);
    cl.println(“”);
    }

    // sets every element of str to 0 (clears array)
    void StrClear(char *str, char length)
    {
    for (int i = 0; i len) {
    return 0;
    }
    while (index < len) {
    if (str[index] == sfind[found]) {
    found++;
    if (strlen(sfind) == found) {
    return 1;
    }
    }
    else {
    found = 0;
    }
    index++;
    }

    return 0;
    }

    Any help on this would be greatly appreciated!!

    regards,

    • Hi Dustin
      In this part:
      if(StrContains(HTTP_req, “GET / “)
      || StrContains(HTTP_req, “GET /index.htm”)) {
      webFile = SD.open(“page1.htm”); // open web page file
      }
      You are checking for the root file (/) or index.htm, but are opening page1.htm
      So either change index.htm to page1.htm in the if statement, or change your file name to index.htm

  123. Great stuff!! Everything is laid out well. I’ve tried the experiments with no issues. Thanks for the continuing education.

    • Hi James
      I had a brief look at the web page that you want to load and it does not seem to be too big that it would cause such a long delay to load. I also see from the Arduino forum that you are using a WiFi shield. I have only tested the tutorial using wired Ethernet. I avoided buying a WiFi shield as there were many reports of bugs and problems with the shields.

      If you can get hold of a wired shield or Ethernet Arduino, then test you project on that. You will then be able to determine if it is the WiFi shield or your project code that is causing the long loading time.

      • Very good idea, I wanted to avoid spending more money but it is worth the test. I can modify the server code to be similar to yours and test the existing SD card with the web files.

        I would not be able to use the ethernet shield as a permanent fixture since this device is mounted on my wall near my blinds, far away from any Ethernet wires.

        I will keep the forum updated. If the problem is the WiFi shield, maybe my solution would be an xbee and an SD card.

        Oh, btw, my original coding worked just fine with the WiFi shield. It was only the SD card implementation that caused the problems. My original code (parts of it) is in my original post from the Aruino forum that I posted above. If you like, you can see what I did originally there.

        Thanks again

        • Hi James
          If your original code worked, then you should hold on before buying an Ethernet shield if you need to save some money.

          Load your original code to the Arduino and then open the Arduino web page that it generates in a browser. Right click the page and choose “View Page Source” (or similar, depending on browser). Now compare it with the SD card version to make sure that nothing has slipped in to cause the error.

  124. Hi Guys,
    im having a problem when i try to use more than 3 conditions/pages with the linking pages code.
    Im using the original code + 3 more pages, if i use 2 more pages with a total of 3 pages (index + 2) everithing works “OK”, but if i add a 4th page, the index.htm does not load, what could it be?

    Part of the code:
    // open requested web page file
    if (StrContains(HTTP_req, “GET / “) || StrContains(HTTP_req, “GET /index.htm”)) {
    webFile = SD.open(“index.htm”); // open web page file
    }
    else if (StrContains(HTTP_req, “GET /page2.htm”)) {
    irsend.sendNEC(0x3FA15E, 32);
    webFile = SD.open(“page2.htm”); // open web page file
    }
    else if (StrContains(HTTP_req, “GET /page3.htm”)) {
    webFile = SD.open(“page3.htm”); // open web page file
    }
    else if (StrContains(HTTP_req, “GET /page4.htm”)) {
    webFile = SD.open(“page4.htm”); // open web page file
    }

  125. Hi, Excellent tutorial. I currently I have my webserver, the but requirement for my project is for me to encrypt and decrypt information, please can you tell me how can this be done, or point me in the right direction

    • Hi Del109
      I haven’t done much research into encrypting for a web server, but the normal way to encrypt a web page is using SSL. I don’t think that an Arduino Uno will have enough processing power to handle encryption / decryption — you will have to try something like the Arduino Due. If you want to avoid having to develop the software yourself, then you can try running the Apache server on a Raspberry PI and put your Arduino behind that.

  126. Just curious is there a way to make the buttons change color with state of button press? i was thinking maybe somehting in here like it changes text in the button.

    if (this.responseXML.getElementsByTagName(‘LED’)[0].childNodes[0].nodeValue === “on”) {
    document.getElementById(“LED1”).innerHTML = “Heater is ON”;
    LED1_state = 1;
    }
    else {
    document.getElementById(“LED1”).innerHTML = “Heater is OFF”;
    LED1_state = 0;
    }

  127. i am able to send option value from web page to arduino for on/off button but how to get different value from the option value and print the value in serial port.

    what i have done is below:

    HTML/JS code:
    ———————————————————————–
    function changeFunc() {
    var selectBox = document.getElementById(“selectBox”);
    var selectedValue = selectBox.options[selectBox.selectedIndex].text;
    strLED1 = selectedValue;

    }

    LED1=1
    LED1=0

    ARDUINO Sketch:
    ————————————————————————————–
    if (StrContains(HTTP_req, “LED1=1”)) {
    LED_state[0] = 1; // save LED state
    digitalWrite(6, HIGH);
    }
    else if (StrContains(HTTP_req, “LED1=0”)) {
    LED_state[0] = 0; // save LED state
    digitalWrite(6, LOW);
    }
    it is working but i want to get option value which is not predefined like “LED1=1” instead receive any value and print in the serial port.

    Please help me i am stuck on this.

    Thanks
    Rakesh

    • Please reply what i have to do to get the option value

      if (StrContains(HTTP_req, “LED1=1″)) {
      LED_state[0] = 1; // save LED state

      }

      how to get the option value which will return the value from the html page
      “StrContains(HTTP_req,” received value from html “)”
      the above one only find the matched value then it execute the function
      i want the output of the StrContains instead of lookup matched value.

      • js
        ————————
        function changeFunc() {
        var selectBox = document.getElementById(“selectBox”);
        var selectedValue = selectBox.options[selectBox.selectedIndex].text;
        strLED1 = selectedValue;

        }

        html
        ——————————————-
        “–
        LED1=1
        LED1=0
        —”

        Sketch
        ————————————————————–
        if (StrContains(HTTP_req, “LED1=1”)) {
        LED_state[0] = 1; // save LED state
        digitalWrite(6, HIGH);
        }
        else if (StrContains(HTTP_req, “LED1=0”)) {
        LED_state[0] = 0; // save LED state
        digitalWrite(6, LOW);

        what i have to change in this to get the string of the option.

  128. Thanks for the tutorial, fantastic .
    In my project , the Analog pin are read status lamps . ( with the ACS712 ) because I see that a wall switch was triggered manually .

    if ( analogRead (2) > 750 ) { LED_state [0] = 1; } else { LED_state [0] = 0; }

    So I have the condition digitalPin ( 2 ) HIGH , but A2 = 0 .
    How to solve this in the arduino ?
    I tried something like this but without success. can someone help me ?

    // LED 1 ( pin 2 )
    if ( ( StrContains ( HTTP_req , ” LED1 = 1 ” ) ) && digitalRead ( 2 ) == HIGH ) {
    digitalWrite ( 2 , HIGH ) ;
    }
    if ( ( StrContains ( HTTP_req , ” LED1 = 1 ” ) ) && digitalRead ( 2 ) == LOW ) {
    digitalWrite ( 2 , HIGH ) ;
    }
    if ( ( StrContains ( HTTP_req , ” LED1 = 0 ” ) ) && digitalRead ( 2 ) == HIGH ) {
    digitalWrite ( 2 , LOW ) ;
    }
    if ( ( StrContains ( HTTP_req , ” LED1 = 0 ” ) ) && digitalRead ( 2 ) == LOW ) {
    digitalWrite ( 2 , LOW ) ;
    }

  129. Hi thanks for a great tutorial series. I am trying to change the color of displayed HTML based on XML response, ie if XML tag contains “OK”, display this in blue, if XML tag contains “Fail” then display this in red. I have found “document.getElementById(“input1″).style.color = ‘#0000FF’;” will change the color okay but I need an if/else to change this based on the contents of the XML tag. I am lost trying to do this. Anyone have suggestions?? Cheers Bruce

    • Hi Bruce,
      you can slove this with .indexOf in Html JavaScript:
      if(xmltag.indexOf(“OK”))document.getElementById(“input1″).style.color=”#0000FF”;
      else document.getElementById(“input1″).style.color=”#FF0000”;
      The code is not tested but should work, just call it after the xmltag was recieved.
      hope this helps you, Springer

  130. I have worked it out, don’t worry, if anyone wants to know the answer is
    document.getElementById(“input2”).innerHTML =
    this.responseXML.getElementsByTagName(‘StbOilSw’)[0].childNodes[0].nodeValue;
    if (document.getElementById(“input2”).innerHTML === “OK”){
    document.getElementById(“input1”).style.color = ‘#0000FF’;
    }
    else {
    document.getElementById(“input1”).style.color = ‘#FF0000’;
    }

  131. Pls.
    how can I add username and password access to the server?
    I would like to connect my IP using DDNS . I need a simple login and password

    Tanks, Saga

  132. Springer, as you can see I worked out another way of doing it but thanks anyway, always good to see another idea and your idea is more compact than mine.
    Any thoughts on how to change color based on value of an analog value returned by the xml? ie engine temp is an analog value returned, it would be nice to change the displayed temp to yellow if over say 80 deg C and in red if over 95 deg. Problem is the value is returned as a text string, not an integer. Cheers Bruce

    • Hi Bruce,
      you can convert numbers in string with the “Number()” function.
      e.g.: console.log(“5″+14) returns “514”, console.log(Number(“5”)+14) returns 19.
      Now you can compare this value to other values (like 80 degrees) and change the color of an element when the temperature is above 80degree, or you can change the color dynamic with the “rgb()” function: http://katalytischerkonverter.com/examples/exampleColorFading
      Springer

      • If u want to change colour based on value u can do this:-

        var num_an = this.responseXML.getElementsByTagName(‘analog’).length;
        for (count = 0; count < num_an; count++) {
        document.getElementsByClassName("analog")[count].innerHTML =
        this.responseXML.getElementsByTagName('analog')[count].childNodes[0].nodeValue;

        var elems = document.getElementsByClassName("analog");
        var arr = [];
        for(var i = 0; i = 304){
        document.getElementById(“analog1″).style.color=”#ff0000”;
        }
        else if (arr <= 303){

        document.getElementById("analog1").style.color="blue";
        }

  133. I was trying to use the switches on A2 and A3 to turn the lights on D6 and D7 on/off using the code below. Where would I put this code snip-it in the main code of Part 16: SD Card Web Server I/O? I’ve tried several different spots, but was unable to ever get it work…

    if (button1State == LOW)
    {
    digitalWrite(6, LOW);
    }
    else{
    digitalWrite(6, HIGH);
    }

    if (button2State == LOW)
    {
    digitalWrite(7, LOW);
    }
    else{
    digitalWrite(7, HIGH);
    }

    • Hi Muldoon
      Is this code meant to run independently of the web page / web server? Do you just want to close or open a switch on A2 and then switch a digital pin high or low?

      Where are you updating or refreshing the values in button1State and button2State?

      • Thank you for helping, and this is a wonderful tutorial and website!

        I was intending for this code to be used with the web page / server. Once I learn how to do this I was going to add more onto it though, but for now, when button1State is pressed /released on the breadboard then the light on pin 6 would turn on/off.

        As for refreshing the values on button1State and button2State, I honestly don’t know. I’m fairly new, but I tried shoving my code just after SetLEDs(); as well as some other places, but nothing seeded to work.

        • Hi Muldoon
          You need to update the variables button1State and button2State with the state of the switches before the code that uses these variables to switch the output pins. If you are using the analog pins with the switches connected as analog pins, you need to read the analog value and decide whether the switch is opened or closed. Based on this, the buttonState variables must be updated.

  134. I’m try to add function for set temperature….like thermostat function…. i would like to set temperature whith buttons….when ds18b20 sensor reaches set temperature it switch on a relay. I was playing whit standard arduino server….and it worked out….but i can not maneged to work it whit ajax server…. does any one have any example of it?

    • Hi Hansp
      Sorry for the late reply, I have been away.
      Yes, it is possible to access the Arduino over the Internet, but you need to enable port forwarding on your router and use a service that handles dynamic IP addresses unless you have a fixed IP address. I will be adding a tutorial on this some time.

      • if you could just tell me how to access my web page through the internet that would be great help!! i need help can figure this out!!

  135. Hi,
    My question is about writing and reading from SD card.
    I need information regarding this scenario.

    I have a PIR sensor and I can control it with you arduino program. From my webpage I can open/close this PIR and I can see the state of this sensor. But when the arduino board reset, the state of this PIR is 0 because it is write in the arduino sketch.
    My question is how can I write the state of this PIR on the SD card and so when arduino restart and read the first time PIR state, it must read it from SD card ??

    Example: PIR is closed from web page….write on sd Card and is saved there….arduino restart because power failure……read the last PIR state from SD card……..display the state in web page…..PIR is closed.

    Can anybody help me with this problem ?
    Thank you.

    • Hi meccip
      It sounds like you just need to write the PIR state to a text file and then read it back. Have a look at the Arduino example code in the IDE at:
      File —> Examples —> SD —> ReadWrite

      • I was thinking about your idea and sound good. I am using your arduino web server program.
        I added some new webdesign, more inputs/outputs ,a connection with netIO controller on android for an easy access from my phone and pushing box for state notifications on my phone.

        I need an example of how to write the state on text file and how to read it from the text file first time when arduino starts. I will try to post here the code with my ideas and maybe you or somebody can help me.

        Thank you.

        • #include
          #include
          #include
          // 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, 113); // IP address, may need to change depending on network
          EthernetServer server(80); // create a server at port 80
          File webFile; // the web page file on the SD card
          char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
          char req_index = 0; // index into HTTP_req buffer
          boolean LED_state[4] = {0}; // stores the states of the LEDs

          1. Do I have to insert a new line…like : File txtfile; //the text file on SD card ??
          2. How it should look the last line (boolean LED_state) to read the state from SD text file or it must be deleted ?

          I was thinking to this line…:
          myFile = SD.open(“ledstate.txt”);
          if (myFile) {


          }
          myFile.close();

          but I don’t know what to write inside the { } and if this line must be in void setup {}

      • I read about EEPROM and I see that writing is limited. My PIR state can be changed many times in one day, so writing in EEPROM is not an option.

        Thank you.

        • Hi meccip
          eeprom write is limited to approx 100,000, read is not limited.
          Even if your PIR changed 100 times a day you have >2.5 years on one eeprom address.
          There are 1024 addresses (bytes) to choose from, so even if your PIR wrote 1000 times a day, you could just change to a new address automatically, with a “for” or “while” loop when the count reaches some number under 100,000.
          Just thought that would be simpler than using an SD card text file.
          Have fun
          Cheers, John

  136. Hello and thank you very much for a very detailed and easy to follow tutorial! Now I know how to set up the Arduino to act as a server, BUT…

    …what I’m looking for is a way of sending a (text) file from my PC to the Arduino, so that the Arduino receives it and saves it on to the SD card. I’m kind of thinking that this is done with some GET magic, but I’m a total noob when it comes to HTTP use. Could you help me out by pointing to the right direction or providing some useful information regarding this issue? Thank you 🙂

    What i would like is to have a web page that I can use to select a file from my computer, click “send” and then the Arduino would get it from the PC. But how, I dunno.

    • Hi Jaakko Fagerlund
      POST is usually used instead of GET for sending files. It is easy to handle this on an Apache web server running PHP, but on the Arduino, you must write all the code to handle the post yourself. Here is some HTML that can be used to select a file using a web page.


      <!DOCTYPE html>
      <html>
      <head>
      <title>Arduino Web Page</title>
      </head>
      <body>
      <form action="" method="POST" enctype="multipart/form-data" id="uploadTxtFile">
      <p>
      <label for="text">Upload text file:</label>
      <input type="file" name="text" id="text">
      </p>
      <p>
      <input type="submit" name="upload" id="upload" value="Upload">
      </p>
      </form>
      </body>
      </html>

      You may also want to try and send the text using Ajax and then saving it to a file on the Arduino.

  137. In Part 2 you mention the problem of locking up if the SD card is not disabled. Is this still an problem with the latest Arduino libraries (v1.0.6)?

    • Hi Scott
      I am not sure about this as I don’t keep track of all the changes to the libraries. You may be able to find a change log for the libraries to see if they made any changes.

      I think that they probably won’t change this as the SD card is not always used with the Ethernet shield and pin 4 that disables the SD card would then be set as an output with a HIGH level on it. This would interfere with a project that does not use the SD card, but uses pin 4 for some other function.

  138. Hi, I really enjoyed the parts of your tutorial series involving AJAX. I knew I needed to learn the basics of it, but was a bit afraid to add more on my ‘to do’ list. The examples work great.

    I am already running an Arduino Home Automation web server which I use to turn on/off lights in my house. My web page links are similar to the HTTP_req used in your examples-I use ‘?device1on’, ‘?device1off’, and ‘?device2on’, so on … My code reads that into readString variable, then acts differently depending on the string sent by the client.

    My question is to incorporate your ‘Arduino AJAX Web Server for Reading a Switch Automatically’ example into my existing web page, can I continue to read the string for both the AJAX request as well as for turning my lights on and off, or does the code in your examples pretty much limit the web server to recognizing only ‘ajax_switch’ as the string? I tried several things to add one link from my existing page to your example, but it seems to only work with the ‘ajax_switch’ string.

    Any help you can provide would be greatly appreciated!

    Thanks

    • Hi Kent
      Where is your existing web page located? Is it on the Arduino and embedded in the sketch, or on an SD card?
      I am not too sure exactly what you are trying to do.

      • It is embedded in the sketch. I chose to do it that way so that I can use conditions to change the page like the following.

        client.println("Living Room");
        client.println("");
        if (digitalRead(relay1) >0){
        client.print("Light is OFF");
        client.println("");
        client.println("Light On");
        }
        else{
        client.print("Light is ON");
        client.println("");
        client.println("Light Off");
        }

        AJAX would come in handy so that once I’ve clicked a link to turn a light off, the state of the relay could be updated on the page reflecting the light is off, and thereby only giving the link to turn it back on. I’m including the readString code that captures the above and acts on it.


        if(readString.indexOf("?device1on") >0)//checks header string for on request
        {
        refreshRequired = 1;
        digitalWrite(relay1, LOW); // set pin 5 low
        allStatesDisplay();
        Serial.println("Living Room Lights On");
        Serial.println("----------");
        Serial.println();
        }
        else{
        if(readString.indexOf("?device1off") >0)//checks header string for off request
        {
        refreshRequired = 1;
        digitalWrite(relay1, HIGH); // set pin 5 high
        allStatesDisplay();
        Serial.println("Living Room Lights Off");
        Serial.println("----------");
        Serial.println();
        }
        }

        Thank you!

        • I should have grabbed code from my most recent sketch (I thought that I was til seeing my post). The refreshRequired = 1; doesn’t work as intended, plus I realize that client.println(""); is a wasted line of code with no html affect to the page.

          Thanks!

  139. Let me try this again.

    I’ve posted my entire Arduino code to http://pastebin.com/c9LpdKC8. I somewhat successfully added your AJAX example to the web page served by my Arduino Mega 2560 R3. The web page is embedded in the sketch. The paragraph that uses the AJAX response is at line 654. The function GetPinState() begins at line 821.

    The thing I seem to have trouble with is when I click a link to turn anything on or off, the browser goes to a blank page. The circuit DOES successfully turn on or off, but I have to either navigate ‘back’ or ‘reload’ the page.

    The ‘refresh’ links I’ve added were my way of getting the updated pin states prior to using your AJAX example. Not very elegant, but it works.

    Do you know how I can use the AJAX, without getting a blank page after clicking a link? I am not sure what I am missing here.

    Thanks in advance for any help you can give!

    • Just in case anyone else wants to know this, but had similar trouble getting to the answer.

      Thanks for responding and then ignoring me. I wouldn’t have asked a question which is answered in a later tutorial had I not been getting frequent ‘500-Internal Server Error’ messages when navigating your site. Therefore, I wasn’t able to see all of the tutorials, though I did try before posting. Thanks anyway !

      • Hi Kent
        Our web host is working on fixing the “500 – internal server error”. It seems to be taking them a long time though.

  140. Hello, I have a question regarding your AJAX server I/O. I would like to use your buttons (LED3, LED4) and create a counter, this counter would send the value to the arduino and then from that value preform other functions (ie. Set Thermostat at value = 50 then have the arduino do things based on the setpoint) I have created a counter button that counts up and down but I cannot seem to get the arduino to parse this data correctly. Later on in your tutorial you show a counter button but do not include the arduino code, can you point me in the right direction here please.

  141. I am trying to add a slider for use with the pwm pins on my arduino Uno
    To control RGB led strip

    Is there someone that got a working slider with this example, I am using example from part 16?

  142. The StrContains function in your code has a bug. For example, it will not find the string “dim” in “cmddimstuff”. Nor will it find it in “cmdidimstuff”.
    The fix is to add
    index -= found;
    immediately before
    found = 0;

    Pete

  143. Please, I need Help.

    I try to get pics from SD card. but when I enter the IP in my computer images usually don’t charge. But When I access the IP through my SmartPhone, images always appear.
    I’m using Chrome, but i tried using Mozila and the same problem

    • To make it work for computer, you have to print in “Content-Type: image/jpg” before sending the image. I handled this by creating an exception that prints this in for images and the standard code (“Content-Type: text/html”) for html requests. It checks the requested file format and sends the corresponding “header”. It worked with “js script, jpg, html, css, bmp, gif” files for me.

  144. Hello,

    Firstly I would like to say what a fantastic and well documented tutorial this is! many thanks for posting all the information to help people like me!

    I was wondering if you have considered doing an example using jQuery? It’s ideal for web apps and the scripts can be linked to external sources (as the SD throughput is slow) and it allows you to make a fantastic GUI for phone or tablet use.

    I have started building a web app to control my central heating controller, switching on and off works great however I have lost the feature where the AJAX result sets the checkboxes when the page reloads. I cannot seem to get the original HTML code to check and uncheck the jQuery check boxes!

    If you have an example of how to do this it would be greatly appreciated!

    Many thanks again!

  145. The ajax example isn’t working for me. The webpage isn’t sending a request. When I run it in my browser and “inspect” it with “F12”, I see the error “access denied”. Google told me that this is a problem with “same origin policy”, but I have no idea how to fix this. The code is working for everyone else, isn’t it? But why am I getting this problem… By the way, other scripts like the “Count Button Clicks” one are working perfectly fine.

  146. I want images instead of buttons to toggle the outputs

    When I press the image it turns into another and vice versa

    Can you help me with this?

    thanks

  147. Hi,
    I would like to use the Arduino Web Server LED Control sketch to control 2 or more led’s. I tried several things but usually one led works but when I try to set the second led on on, the other one goes off. Is there an easy way to make this work?
    Really great tutorial, thanks for sharing.
    Stan

  148. Hello, is it possible to store BOOTSTRAP on SD?

    I’m trying to create a project where I want to provide pages on an Arduino Wev Server with polish CSS and graphics. I can do it if the PHP server and Bootstrap pages are on a Raspberry, but I want one variant with Arduino doing all the job. Is it possible to put my pages and all the Bootstrap files on SD an put them to work?

    • Hey! I don’t really know what you’re trying to achieve because I’m not too sure about what bootstrap is :)… It’s some kind of framework, that’s all I get.
      To your question, it’s possible to get almost everything of a real website working. I “tuned” the webserver tutorial code and now I’m able to host any webpage consisting of .css .js .htm .jpg files. It extracts the file names out of the requests and so I don’t have to change the code if I rename (or move folders on the sd) files. I’m having difficulties implementing Ajax, but the basics are working.

      .php could get really hard to get it work. It’s supposed to be running on the server, so you’d have to write some sort of interpreter for the arduino. This would be pretty slow and probably not the best solution. I think it would be less of a problem to create similar functions in arduino code and run them directly than to try implementing php.

  149. Thank you for sharing these fantastic articles. They are extremely well written and are exactly what I was looking for. The only thing I would like to see is some form of authentication, but it’s not critical for my project at this time.

    Regards,

    Les

    • Theoretically it should work, but I do not have a WiFi shield myself to test it. The only reason that it would not work is if there are problems or issues with the WiFi shield or library.

      • To get it to work, you have to change the function names. Some of them used in this tutorial don’t exist or are not needed with wlan. I found it easier to modify the “wifi webserver” arduino example than to port the code from the Ethernet shield. The examples here and the arduino ones use a little bit different “mechanisms” but I got almost all parts of this tutorial working by adding small changes to the arduino code.

  150. I’m following your interesting tutorial, I have a problem in part 5 Arduino Web Server LED Control, the sketch works well but when I Uncheck the checkbox on my web browser the led goes off but after few seconds (1 or less) the led turns back on. I tried to solve problem adding more delay on browser updating but the trouble persists.
    Regards
    Ale

  151. Hi,

    I have just started to design my UI/webpage for my project. As it is to be accessed from mobile devices I wanted to have nice big buttons/icons to click. The idea is to have some icons that are clickable and change image depending on the state, and also to have icons that change image depending on switch/sensor values. Is this possible using the Arduino web server?

    Regards,

    Les

    • It should be possible with the Arduino web server. You will need to make sure that the server handles all the image types that you want to use for icons.

      • Thanks for the reply. I have managed to get it all working so far. I had some stupid typo errors that caused issues with the XML, (Is there a way to display/debug the XML from within the browser?) but other than that no problems. The next question is how best to deal with images, rather than check for each individual image can I perhaps use wildcards? Lastly it seems pretty slow to send the images via the sdcard, they are only small, 3-4KB but I can see them being drawn almost line by line.

        Thanks for your help.

        Les

        • I’m not sure about browser debug info for XML, try and Google it and also check if the FireBug plug-in for Firefox has something for that.
          The Arduino is pretty slow delivering images because it is only an 8-bit microcontroller communicating over a serial link to the Ethernet chip. Which Arduino are you using? I assume the 32-bit Arduino (Due) will have faster Ethernet, but have not tested it myself.

          • I am actually using a Teensy 3.1 (32bit arm @ 96Mhz). I have just done some SD benchmarking and found the SdFat library is 4 times faster but I haven’t tried it with the web server yet so don’t know where the bottleneck is.

            Regards,

            Les

          • Wow, I didn’t expect that you were using a 32-bit Arduino. I just assumed that it would be an 8-bit one when you said that the images load slow.

  152. I tried the other SD library and it didn’t help. I guess the bottleneck is the code, reading and sending 1 byte at a time is not terribly efficient. If you don’t mind I am going to post code based on Part 11 in the Teensy forum (with links to your site of course) and see if anyone has any suggestions.

    Regards,

    Les

    • No problem. Maybe post a link here back to forum as well to help people searching for the same thing on this blog.

      • Hi,

        I post in the Teesny forum here…https://forum.pjrc.com/threads/27556 and already have some new code which is much faster, just by buffering the image send.

        I forgot to mention it before but it caught me out and might be worth mentioning. Don’t forget the SD file names are 8.3 format.

        Lastly as a final addition to my project it would be nice if I could add some click sounds, is this possible?

        Regards,

        Les

        • I have not used sounds myself. I do know that you can use the HTML5 <audio> tag, but there are browser compatibility issues with the audio formats – not all browsers support a single format. You will need to write the server code to handle the fetching of the audio file and probably activate the playing of the file through JavaScript (on click). As far as I know, HTML5 games still use Flash for audio because of various issues.

          Also if you have lots of small icon images, you can merge them into one image file as a strip of images, and then use CSS to display the relevant icon in each part of the HTML. In this way, there will only be one fetch of an image file, reducing the number of server requests for the images. This should also speed up your server.

          • Thanks again for the help.

            I was able to get the audio working quite easily with the tag.

            The CSS sprites was also quite easy once I googled it, and again it’s made things faster and easier on the code side.

            Lastly, answering my own question, in Chrome you can see the xml using the developer tools.

            Regards,

            Les

  153. Bonjour, vous dites :”Il serait plus fiable pour vérifier où le LED2 = 2 texte est dans le message HTTP afin de déterminer si la case est cochée ou décochée. Ce serait alors rendre impossible pour l’état de la LED et l’état de la case à cocher pour devenir non synchronisé. J’ai essayé de modifier le code mais je n’y arrive pas. Comment faire cela ? Et comment remplacer la case à cocher par un bouton on/off ? Merci par avance.

  154. Hi Les

    How did you get Chrome DevTools to display the XML? I can see outgoing GET requests but not the incoming XML.

    Regards
    Bruce

  155. Hi Bruce,

    Open the dev tools and click on Network. On the left you will see lines scrolling with ajax_inputs@nocache, click on one and then preview in the middle and you should see the xml.

    Regards,

    Les

  156. Thank you for the great information you have shared. I am very new to arduino, I just started learning last week.

    I am having problems with Part 9: reading an analog input and switches using ajax. I am only interested in getting analog values so I removed the switches code. I am using Internet Explorer 6 so I had to change var request = new XMLHttprequest () to var request = new ActiveXObject(‘MSXML.XMLHTTP.3.0’) Other than that I have not changed any of the other code.

    When the webpage comes up it only shows the heading nothing else. When I check the serial monitor it shows that it is getting the GET / ajax_switch&nocache.

    If I change (HTTP_req.indexOf (“ajax_switch”)> -1) to ==-1 the webpage then only shows “Analog A2: 505″ it does not update the code every second. This also happens if I comment out the HTTP_req =” “.

    Do you have an idea of how I can get the code to work properly?

    Thank you for any help.

  157. Great Tutorial.

    Really helped me a lot during me project.

    Question:
    I could operate my application of turning LEDs using different buttons. However I was trying to make to visually attractive and easy to use.

    Lets say I am doing Home automation using the same then the GUI should be an image of the apartment rooms and when I click on particular zone only that particular zone’s lights are turned on.

    Kindly help me how to send data after clinking on the image.

  158. Merci pour la grande information que vous avez partagé. Je veux faire une application androïde (allumer et atteindre l’ampoule grâce à mon Smartphones) avec une carte arduino+ bouclier de wifi arduino. Ma question est: s’il vous plaît me dire s’il est possible de le faire avec un bouclier de wifi à la place d’un bouclier Ethernet?

  159. Thank you for Great Tutorial !:)
    I have a problem with Part 16: In my progect i want to realize lighting control with Arduino web server + 433 MHz transmitter, but when i add string (mySwitch.send(13746956, 24); – RF transmitter comand) instead of (digitalWrite(10, HIGH);) in void SetLEDs:
    // LED 3
    if (StrContains(HTTP_req, “LED3=1”)) {
    LED_state[2] = 1; // save LED state
    mySwitch.send(13746956, 24);
    //digitalWrite(10, HIGH);
    }
    the web server stops working – web page is not loading…

    Can you help me with my problem?
    Link to download sketch:
    https://drive.google.com/open?id=0B6rOXTl_OoAqfkV2cTIxSzBGWHBMS2ttWTVQYnpTN2wtNk8xUmJldTd3TmhST1NoUlp5R0E&authuser=0

    • Hi krugmad

      Does the web server stop working just by adding the new line of code, or when the new line of code is run?

      Which Arduino are you using. It is possible that the Arduino is running out of memory and hanging because of this.

      • Thanks for quick reply!
        I use the Arduino Uno. Web server stops working when the new line of code is run. The size of scetch with all added linnes is 28000 of 32000 bytes.

        I tell an example:
        1 step: I upload a sketch (from my download link) to Arduino Uno and open the web page in brouser – it works well, but light doesnot work, couse line in scatch responsible for the light is located in the “comments”.
        2 step: The web page still open and I change the scatch – delete comment in line
        if (StrContains(HTTP_req, “LED3=1”)) {
        LED_state[2] = 1; // save LED state
        mySwitch.send(13746956, 24);
        //digitalWrite(10, HIGH);
        }
        and download this scatch in Arduino – now light switch starts working. But if I close the web page and try to open it again – the web page refuses to be opened.

        My problem – when I download the full scatch (with RF transmitter lines) web page is not loading.

        • If it is a memory problem, then it won’t be the amount of Flash memory used, but a problem with the RAM size. Do you have an Arduino Mega that you can try the sketch with to see if the bigger RAM size on the Mega solves the problem?

          • Thank you for reply, I appreciate your help !:)
            I don’t have yet Arduino Mega, , I should probably buy it.
            I’ll try to put some code in EEPROM memory, may be it’ll give a result.

  160. Hi, thanks for your info, it’s a great project. What if I want to add an DHT11 Temp Sensor? How should I show the temperature through AJAX/XML as an HTML caption?

    • It would work the same way as sending an analog value. Take a look at how the analog values are sent to help you get started.

      • I just did it and it worked, but when two clients connect at the same time the leds bright 5 or 6 seconds later, I mean, I click the check box, the arrow flash and 5 or 6 seconds later the led gets on. What could be wrong?, Thanks for your help.

  161. Can you please send me a working ajax script to contron 24 outputs Organized in boxes 2 by 2? Mine won’t work. Please? I have tried for almost one month one hour a day to get it to work. Can you? Please?

  162. Pingback: Arduino MEGA Ethernet Web Server for Controlling 24 Outputs | Starting Electronics Blog

  163. Pingback: Proyectos final de curso | Aprendiendo Arduino

  164. hello,
    for the firt: thanks for this great toturial !!!!!!!!
    it helps me a lot for a better understanding,

    but i have a problem:
    i tried out step Eleven to create a webserver with sd-card. the part with the links works fine for me but the Image won’t be displayed at my Computer (Firefox) it’s the same with my Android tablet.
    once obove you gave instructions to solve the problem but i think i made it wrong. (changing the Content type to Image/jpg)
    could you give me a short example how to create a solution that pics can be showed at pc-firefox.
    thanks for all and sorry, i’ m a beginner

    markus

  165. hello guys,
    ok, problem is solved, my misstake.
    i didn’t straight follow the toturial.
    now the images are displayed.

    again thanks for this great toturial!!!

    regards
    markus

  166. hi

    i just wanted to say thanks for your tutorial. i used your tutorial back in 2013 to help me understand the implementation of arduino technology, and it assisted me greatly. with the help of your site in assisting me, I was able to get an A for my final year degree project

  167. hi,
    how can i include image in the web page? ,for that what change i have to make in the coding and can i include any authentication in the coding?
    plz reply it wilol be very useful for my project?

    also,instead of html can we include php file in the project?

  168. thank u so much for ur reply!

    i found a code in the below link
    http://playground.arduino.cc/Code/WebServerST (new webserverST code)
    i thought to use that code,in that code mytest.php is defined.wat does it mean?
    is it a php file?

    is that code is similar like ur code in application or is it different?i thought to combine both coding?is it possible?i dont understand that?
    plz help me!
    Thanks in advance!

    • It looks like the PHP file is used as some sort of test. There does not seem to be any documentation and not enough comments in the code to know what it is for. You would have to analyse the code to find out what it is for or else ask the author on the Arduino forum. There is certainly not a PHP interpreter implemented in the code.

      The difference between my code and the code that you are referring to is this:
      1) My code is part of a tutorial and is there to teach some basics on the technologies used in building a web server.
      2) Because my code is written for teaching, it does not contain error handling and will not be reliable in every situation because it has not been made to be robust.
      3) The code that you are referring to has probably been designed to be reliable and looks like it can handle multiple file types such as external CSS and JavaScript files, zip files, pdf files, different types of image files, etc. I am guessing a bit here and have only looked over the code briefly, but it definitely seems to handle multiple file types.
      4) In other words, the code that you are referring to looks like it is a complete web server made to handle multiple file types, while my code is to teach some principles and web technologies so that you can design your own web server.

      • NO WORDS TO THANK U,THANK U SO MUCH!
        NOW I HAVE GOT SOME IDEA ABOUT THE CODING AND WHAT CAN BE DONE WITH IT.

        I GET BACK U, WHEN I GET STUCK UP SOMEWHERE!

  169. Why is it, that only works for me when I’m connected through the LAN? If I try to connect from internet using port forwarding (as I already do with my Raspberry Pi), it only shows a blank page (no 404 error, literally a blank page) with the correct title in the chrome (explorer) tab. Now, if I load the page connected to the LAN and then switch my connection to internet (with the page already loaded), it works like a charm. I´m pretty confused here. :s

      • Hmm.. no, I haven’t, because I want to use the AJAX part to show analog and digital values in real time. I don’t know why it doesn’t work over internet, it’s pretty confusing to me that only works whitin the LAN. :S

        I’ll keep checking and post something useful if found.

  170. HI,
    i would like to interface an LCD with this web server to display as “EMBEDDED WEB SERVER” along with ur web server functionality. is it possible?
    i thought to use only two LEDs, one using checkbox & other using button,
    also i thought to use three switches and no analog values.so that i can save pins for LCD display.Hence, i decided to use
    pins 2,3,4,5,11,12 for LCD display and
    6,7 for LEDs and
    8,9,10 for switches.
    so,is this will work or not?if it will works what are the changes i have to make in the coding?
    plz help!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    • Hi akipeed
      Are you only going to use the LCD to display that one line of text?
      From what you have described, it should work fine.
      You would need to add the LCD initialization code and write the text to the LCD at the start up.
      Then just modify the code to move the LEDs and switches to the pins that you want to use.
      Everything is explained in the tutorial, so if you follow the tutorial and analyse the code, you should be able to make the changes.
      Let us know how it goes.

  171. HI,
    i have understood the coding and modified it according to my requirements but i dont understand the below part so i cant able to modify it, can u explain it what this part of coding mean?which string “str” refers to?
    plz help me!

    // sets every element of str to 0 (clears array)
    void StrClear(char *str, char length)
    {
    for (int i = 0; i len) {
    return 0;
    }
    while (index < len) {
    if (str[index] == sfind[found]) {
    found++;
    if (strlen(sfind) == found) {
    return 1;
    }
    }
    else {
    found = 0;
    }
    index++;
    }

    return 0;
    }

    • I’m not sure what happened to that code, but it does not look like the original. I may be because you did not copy and paste it as code, but it looks like two functions have merged. I think that this is the original code:

      // 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;
      }
      
      


      The first function is StrClear(). When you pass a string or array to it, the string or array is referred to as str.
      All this function does is set every element of the array to 0 for length number of array elements.

      The same in the second function StrContains() is passed two strings which take on the names str and sfind. This function searches for the second string passed to it to see if it can be found in the first string that is passed to it.

      • oh very sorry! i made a mistake here.thank u so much for notifying me abt the mistake.i have understood the concept but here what does “str” refers to?i.e., which string it refers to, is it LED,SWITCHES OR ANALOG VALUES.I DONT UNDERSTAND IT!!!

        • In this case it is referring to the array HTTP_req which contains the HTTP request from the web browser. You can tell this by looking at the function calls, for example:
          StrClear(HTTP_req, REQ_BUF_SZ);
          Is passing HTTP_req to the function, so in the function, str is now used to refer to HTTP_req.

  172. Pingback: Tema 5 – Taller de Proyectos con Arduino | Aprendiendo Arduino

  173. HI
    i have done LCD interfacing with arduino but the LCD is not displaying.i dont no what is the reason?
    usually Arduino uno will be on COM 3 while i am doing web server experiment and it works fine.but while i am doing this LCD interfacing exp, port is set to COM2 AUTOMATICALLY.I THINK THIS IS THE REASON FOR NOT DISPLAYING ANYTHING.what to do to change the port to COM3 while connecting the LCD.HOW TO CLEAR THIS ERROR?
    PLZ HELP!!!!!!!!!!!!

    • The COM port number should not make any difference. If you can upload your code to the Arduino, then your sketch should run. COM port numbers usually change if you plug a device into a different USB port from previously. If you can load and run the blink example sketch from the examples in the Arduino IDE, then everything is working.
      Try to run one of the LCD test sketches from the IDE examples to see that the hardware is connected properly. Also check that the LCD contrast is set up so that you can read text on the LCD.

      • hi, i have connected lcd successfully to my arduino using examples but i would like to do that in http://playground.arduino.cc/Code/WebServerST (new webserverST code) code to display as web server.i tried many times at first it displays correctly but after that it doesnt.so where should i include lcd.print(“WEB SERVER!”); command in that code to work properly!
        plz help me!!!!!!!!!!!

        • Are you trying to do this on an Arduino Uno? If you are using an Uno, chances are that there is not enough memory (RAM) available.
          If you just want to display some static text on the LCD, then it should work by putting it in the setup() function. You should not need to put it in the loop() function.

          • THANKS FOR UR REPLY!
            TILL NOW SD CARD WORKED PROPERLY,BUT NOW IT SHOWS SD CARD INITIALIZATION FAILED.
            EVERYTHING IS DONE AS PER UR SD CARD INITIALIZATION VIDEO.WHAT MAY BE THE REASON FOR THE FAILURE OF INITIALIZATION ?

          • Have you tested the SD card using one of the basic SD card sketches from the Arduino IDE examples to see if the SD card is still working?

  174. Pingback: KBØASQ » Power Management Unit Build – Part 5

  175. Pingback: Power Management Unit Build – Part 5 | Flatwater Trading Post

    • i have made the following changes in the below code

      #include
      #include
      #include

      // 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, 3); // IP address, may need to change depending on network
      EthernetServer server(80); // create a server at port 80
      File webFile; // the web page file on the SD card
      char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
      char req_index = 0; // index into HTTP_req buffer
      boolean LED_state[4] = {0}; // stores the states of the LEDs

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

      Serial.begin(115200); // 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.”);
      // switches on pins 2, 3 and 5
      pinMode(2, INPUT);
      pinMode(3, INPUT);
      pinMode(5, INPUT);
      // LEDs
      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);

      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
      // limit the size of the stored received HTTP request
      // 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.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) {
      // send a standard http response header
      client.println("HTTP/1.1 200 OK");
      // remainder of header follows below, depending on if
      // web page or XML page is requested
      // Ajax request – send XML file
      if (StrContains(HTTP_req, "ajax_inputs")) {
      // send rest of HTTP header
      client.println("Content-Type: text/xml");
      client.println("Connection: keep-alive");
      client.println();
      SetLEDs();
      // send XML file containing input states
      XML_response(client);
      }
      else if { // web page request
      // send rest of HTTP header
      client.println("Content-Type: text/html");
      client.println("Connection: keep-alive");
      client.println();
      // send web page
      webFile = SD.open("index.htm"); // open web page file
      }

      else if (StrContains(HTTP_req, "GET /page2.htm")) {
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println("Connnection: close");
      client.println();
      webFile = SD.open("page2.htm"); // open web page file
      }
      else if (StrContains(HTTP_req, "GET /pic.jpg")) {
      webFile = SD.open("pic.jpg");
      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();
      }

      // display received HTTP request on serial port
      Serial.print(HTTP_req);
      // 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)
      }

      // checks if received HTTP request is switching on/off LEDs
      // also saves the state of the LEDs
      void SetLEDs(void)
      {
      // LED 1 (pin 6)
      if (StrContains(HTTP_req, "LED1=1")) {
      LED_state[0] = 1; // save LED state
      digitalWrite(6, HIGH);
      }
      else if (StrContains(HTTP_req, "LED1=0")) {
      LED_state[0] = 0; // save LED state
      digitalWrite(6, LOW);
      }
      // LED 2 (pin 7)
      if (StrContains(HTTP_req, "LED2=1")) {
      LED_state[1] = 1; // save LED state
      digitalWrite(7, HIGH);
      }
      else if (StrContains(HTTP_req, "LED2=0")) {
      LED_state[1] = 0; // save LED state
      digitalWrite(7, LOW);
      }
      // LED 3 (pin 8)
      if (StrContains(HTTP_req, "LED3=1")) {
      LED_state[2] = 1; // save LED state
      digitalWrite(8, HIGH);
      }
      else if (StrContains(HTTP_req, "LED3=0")) {
      LED_state[2] = 0; // save LED state
      digitalWrite(8, LOW);
      }
      // LED 4 (pin 9)
      if (StrContains(HTTP_req, "LED4=1")) {
      LED_state[3] = 1; // save LED state
      digitalWrite(9, HIGH);
      }
      else if (StrContains(HTTP_req, "LED4=0")) {
      LED_state[3] = 0; // save LED state
      digitalWrite(9, LOW);
      }
      }

      // send the XML file with analog values, switch status
      // and LED status
      void XML_response(EthernetClient cl)
      {
      int analog_val; // stores value read from analog inputs
      int count; // used by 'for' loops
      int sw_arr[] = {2, 3, 5}; // pins interfaced to switches

      cl.print("”);
      cl.print(“”);
      // read analog inputs
      for (count = 2; count <= 5; count++) { // A2 to A5
      analog_val = analogRead(count);
      cl.print("”);
      cl.print(analog_val);
      cl.println(“”);
      }
      // read switches
      for (count = 0; count < 3; count++) {
      cl.print("”);
      if (digitalRead(sw_arr[count])) {
      cl.print(“ON”);
      }
      else {
      cl.print(“OFF”);
      }
      cl.println(“”);
      }
      // checkbox LED states
      // LED1
      cl.print(“”);
      if (LED_state[0]) {
      cl.print(“checked”);
      }
      else {
      cl.print(“unchecked”);
      }
      cl.println(“”);
      // LED2
      cl.print(“”);
      if (LED_state[1]) {
      cl.print(“checked”);
      }
      else {
      cl.print(“unchecked”);
      }
      cl.println(“”);
      // button LED states
      // LED3
      cl.print(“”);
      if (LED_state[2]) {
      cl.print(“on”);
      }
      else {
      cl.print(“off”);
      }
      cl.println(“”);
      // LED4
      cl.print(“”);
      if (LED_state[3]) {
      cl.print(“on”);
      }
      else {
      cl.print(“off”);
      }
      cl.println(“”);

      cl.print(“”);
      }

      // sets every element of str to 0 (clears array)
      void StrClear(char *str, char length)
      {
      for (int i = 0; i len) {
      return 0;
      }
      while (index < len) {
      if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
      return 1;
      }
      }
      else {
      found = 0;
      }
      index++;
      }

      return 0;
      }

      can u plz guide me, where i have done mistake which shows that error

      • only i have made the following change in the above code

        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) {
        // send a standard http response header
        client.println(“HTTP/1.1 200 OK”);
        // remainder of header follows below, depending on if
        // web page or XML page is requested
        // Ajax request – send XML file
        if (StrContains(HTTP_req, “ajax_inputs”)) {
        // send rest of HTTP header
        client.println(“Content-Type: text/xml”);
        client.println(“Connection: keep-alive”);
        client.println();
        SetLEDs();
        // send XML file containing input states
        XML_response(client);
        }
        else if { // web page request
        // send rest of HTTP header
        client.println(“Content-Type: text/html”);
        client.println(“Connection: keep-alive”);
        client.println();
        // send web page
        webFile = SD.open(“index.htm”); // open web page file
        }

        else if (StrContains(HTTP_req, “GET /page2.htm”)) {
        client.println(“HTTP/1.1 200 OK”);
        client.println(“Content-Type: text/html”);
        client.println(“Connnection: close”);
        client.println();
        webFile = SD.open(“page2.htm”); // open web page file
        }
        else if (StrContains(HTTP_req, “GET /pic.jpg”)) {
        webFile = SD.open(“pic.jpg”);
        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();
        }

  176. i have planned to include an image and a link to the web server tutorial specified in Part 16: SD Card Web Server I/O .when i modified the code i get the following error messages which is given below

    Arduino: 1.6.1 (Windows 7), Board: “Arduino Uno”

    eth_websrv_SD_Ajax_in_out.ino: In function ‘void loop()’:

    eth_websrv_SD_Ajax_in_out.ino:88:29: error: expected ‘(‘ before ‘{‘ token

    eth_websrv_SD_Ajax_in_out.ino:97:25: error: expected ‘}’ before ‘else’

    eth_websrv_SD_Ajax_in_out.ino:126:21: error: ‘c’ was not declared in this scope

    eth_websrv_SD_Ajax_in_out.ino: At global scope:

    eth_websrv_SD_Ajax_in_out.ino:140:1: error: expected declaration before ‘}’ token

    Error compiling.

    This report would have more information with
    “Show verbose output during compilation”
    enabled in File > Preferences.

  177. I need to get picture from SD card. but when I enter the IP in my computer image is not displaying in the html page ,does i have to include any command in the coding?
    plz help

    • Hi akipeed
      You need to look at how images are handled in this part of the tutorial: http://startingelectronics.org/tutorials/arduino/ethernet-shield-web-server-tutorial/SD-card-web-server-image/
      Because this is a series of tutorials that explains various concepts, the code in other parts of the tutorial do not include code that handles images. The idea of the tutorial series is to study each part and understand it so that you can then design your own web server. I think that there is a need for a general purpose web server that handles various file types and I want to design and add one soon which I think will be a big help to many people.

      • thanks for ur reply!!!!!!!!!!!!11

        If u post general purpose web server design that handles various file types,it will be a great help to everyone.

        i will be very grateful to u if u post it within this month as soon as possible becoz it will be very helpful for my final year project!!!!!!!!!!!!!!!!!!!!!!

  178. Hi! I was wondering how to write a code for the arduino Atmega with the official shield to make these pages work:

    Note from moderator: removed the code that did not display properly and correctly formatted it in the second post below.

    First One:
    Second One:
    Third One:

    And for the first one: How do I redirect to the second page when I type in the correct password?

    Second one: How do I redirect to the third page after 3 seconds?

    P.S: Sorry about the Swedish in the website, but I think that you can help me anyways. 😉 And sorry for the long comment! I would have put a picture of a coding potato here if I could (9gag joke) 😉

    • P.S give me your e-mail so that I can send you pictures of what you are helping me to build 😉

    • P.S saw that your site took my code for code and printed out what it was supposed to do, so here I go again:

      page1.htm

      <!DOCTYPE html>
      <html>
      <html lang="en">
          <head>
      	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      	<title>Login</title>
      <style>
      	#wrap { 
      		width: 1000px; 
      		margin: 0 auto; 
      	}
              .out_box {
                  float: left;
                  margin: 20px 20px 20px 20px;
                  border: 1px solid black;
                  padding: 0 5px 0 5px;
                  min-width: 280px;
              }
      
              input {
                  margin: 10px;
              }
              input {
                  vertical-align: -3px;
              }
              h1 {
                  font-size: 400%;
                  color: black;
                  margin: 0 0 10px 0;
      	    text-align: center;
              }
              h2 {
                  font-size: 100%;
                  color: black;
                  margin: 5px 0 5px 0;
      	    text-align: center;
              }
              h3 {
                  font-size: 95%;
                  color: black;
                  margin: 5px 0 5px 0;
              }
              h4 {
                  font-size: 200%;
                  color: black;
                  margin: 5px 0 5px 0;
      	    text-align: center;
              }
              p, form, button {
                  font-size: 80%;
                  color: #252525;
              }
              .small_text {
                  font-size: 70%;
                  color: #737373;
              }
      	body {
          background-color: lightblue;
      	}
          </style>
          </head>
      
      
      	<body>
      
      
      
      	<div id=wrap>
      	<h1>Login</h1>
      	<div style="text-align:center"> 
      	<h2>Link to session validation:</h2>  <a href=validating.htm> Validate Session</a> 
      	</div>
      	</div>
      	</body>
      	</html>
      
      

      Second One:

      validating.htm

      <!DOCTYPE html>
      <html>
      <html lang="en">
          <head>
      	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      	<meta http-equiv="refresh" content="3; url=index3.htm" />
      	<title>Login</title>
      <style>
      	#wrap { 
      		width: 1000px; 
      		margin: 0 auto; 
      	}
              .out_box {
                  float: left;
                  margin: 20px 20px 20px 20px;
                  border: 1px solid black;
                  padding: 0 5px 0 5px;
                  min-width: 280px;
              }
      
              input {
                  margin: 10px;
              }
              input {
                  vertical-align: -3px;
              }
              h1 {
                  font-size: 400%;
                  color: black;
                  margin: 0 0 10px 0;
      	    text-align: center;
              }
              h2 {
                  font-size: 100%;
                  color: black;
                  margin: 5px 0 5px 0;
      	    text-align: center;
              }
              h3 {
                  font-size: 95%;
                  color: black;
                  margin: 5px 0 5px 0;
              }
              h4 {
                  font-size: 200%;
                  color: black;
                  margin: 5px 0 5px 0;
      	    text-align: center;
              }
              p, form, button {
                  font-size: 80%;
                  color: #252525;
              }
              .small_text {
                  font-size: 70%;
                  color: #737373;
              }
      	body {
          background-color: lightblue;
      	}
      	.button {
          background-color: #ddcccc;
          border: 1px solid black;
          color: black;
          font-family: Arial;
          font-size: small;
          text-decoration: none;
          padding: 3px;
      }
          </style>
      
      
          </head>
      
      
      	<body>
      	<div id=wrap>
      	<h1>Validating</h1>
      	<div style="text-align:center"> 
      	</div>
      	</div>
      
      <script type="text/javascript">
      function callback(a){
          return function(){
          	alert(a);
          }
      }
      var a = ”test”;
      setTimeout(callback(a), 2000);
      
         </script>
      
      	</body>
      	</html>
      
      

      Third One:

      index3.htm

      <!DOCTYPE html>
      <html>
      <html lang="en">
          <head>
      	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
              <title>Arduino MEGA 24 Output</title>
              <script>
              strLED = "";
      
              function GetArduinoIO()
              {
                  nocache = "&nocache=" + Math.random() * 1000000;
                  var request = new XMLHttpRequest();
                  request.onreadystatechange = function()
                  {
                      if (this.readyState == 4) {
                          if (this.status == 200) {
                              if (this.responseXML != null) {
                                  // XML file received - contains LED states
                                  var re;
                                  var num_LEDs;
                                  var i;
                                  var ledstr = "";
                                  
                                  re = this.responseXML.getElementsByTagName('LED');
                                  num_LEDs = re.length;
                                  
                                  for (i = 0; i < num_LEDs; i++) {
                                      ledstr = "LED" + (i + 1);
                                      if (re[i].childNodes[0].nodeValue === "checked") {
                                          document.getElementsByName(ledstr)[0].checked = true;
                                      }
                                      else {
                                          document.getElementsByName(ledstr)[0].checked = false;
                                      }
                                  }
                              }
                          }
                      }
                  }
                  // send HTTP GET request with LEDs to switch on/off if any
                  request.open("GET", "ajax_inputs" + strLED + nocache, true);
                  request.send(null);
                  setTimeout('GetArduinoIO()', 1000);
                  strLED = "";
              }
              // service LEDs when checkbox checked/unchecked
              function GetCheck(led_num_str, cb)
              {
                  if (cb.checked) {
                      strLED += ("&" + led_num_str + "=1");
                  }
                  else {
                      strLED += ("&" + led_num_str + "=0");
                  }
              }
          </script>
          <style>
      	#wrap { 
      		width: 1000px; 
      		margin: 0 auto; 
      	}
              .out_box {
                  float: left;
                  margin: 20px 20px 20px 20px;
                  border: 1px solid black;
                  padding: 0 5px 0 5px;
                  min-width: 280px;
              }
      
              input {
                  margin: 10px;
              }
              input {
                  vertical-align: -3px;
              }
              h1 {
                  font-size: 400%;
                  color: black;
                  margin: 0 0 10px 0;
      	    text-align: center;
              }
              h2 {
                  font-size: 100%;
                  color: black;
                  margin: 5px 0 5px 0;
              }
              h3 {
                  font-size: 95%;
                  color: black;
                  margin: 5px 0 5px 0;
              }
              h4 {
                  font-size: 200%;
                  color: black;
                  margin: 5px 0 5px 0;
      	    text-align: center;
              }
              p, form, button {
                  font-size: 80%;
                  color: #252525;
              }
              .small_text {
                  font-size: 70%;
                  color: #737373;
              }
          </style>
          </head>
          <body onload="GetArduinoIO()">
      	<div id="wrap">
              <h1>Modelltågskontroll V1.0</h1>
      	<h4>V&auml;xlar:</h4>
              <div class="out_box">
      		<h2>Rel&auml; 1</h2>
                  <form class="check_LEDs" name="LED_form1">
      		<h3>V&auml;xel 1</h3>
                      <input type="checkbox" name="LED1" value="0" onclick="GetCheck('LED1', this)" />V&auml;nster
                      <input type="checkbox" name="LED2" value="0" onclick="GetCheck('LED2', this)" />H&ouml;ger<br />
      		<h3>V&auml;xel 2</h3>
                      <input type="checkbox" name="LED3" value="0" onclick="GetCheck('LED3', this)" />V&auml;nster
                      <input type="checkbox" name="LED4" value="0" onclick="GetCheck('LED4', this)" />H&ouml;ger
                  </form>
                  <form class="check_LEDs" name="LED_form2">
      		<h3>V&auml;xel 3</h3>
                      <input type="checkbox" name="LED5" value="0" onclick="GetCheck('LED5', this)" />V&auml;nster
                      <input type="checkbox" name="LED6" value="0" onclick="GetCheck('LED6', this)" />H&ouml;ger<br />
      		<h3>V&auml;xel 4</h3>
                      <input type="checkbox" name="LED7" value="0" onclick="GetCheck('LED7', this)" />V&auml;nster
                      <input type="checkbox" name="LED8" value="0" onclick="GetCheck('LED8', this)" />H&ouml;ger
                  </form>
              </div>
              <div class="out_box">
      	<h2>Rel&auml; 2</h2>
                  <form class="check_LEDs" name="LED_form3">
      		<h3>V&auml;xel 5</h3>
                      <input type="checkbox" name="LED9" value="0" onclick="GetCheck('LED9', this)" />V&auml;nster
                      <input type="checkbox" name="LED10" value="0" onclick="GetCheck('LED10', this)" />H&ouml;ger<br />
      		<h3>V&auml;xel 6</h3>
                      <input type="checkbox" name="LED11" value="0" onclick="GetCheck('LED11', this)" />V&auml;nster
                      <input type="checkbox" name="LED12" value="0" onclick="GetCheck('LED12', this)" />H&ouml;ger
                  </form>
                  <form class="check_LEDs" name="LED_form4">
      		<h3>V&auml;xel 7</h3>
                      <input type="checkbox" name="LED13" value="0" onclick="GetCheck('LED13', this)" />V&auml;nster
                      <input type="checkbox" name="LED14" value="0" onclick="GetCheck('LED14', this)" />H&ouml;ger<br />
      		<h3>V&auml;xel 8</h3>
                      <input type="checkbox" name="LED15" value="0" onclick="GetCheck('LED15', this)" />V&auml;nster
                      <input type="checkbox" name="LED16" value="0" onclick="GetCheck('LED16', this)" />H&ouml;ger
                  </form>
              </div>
              <div class="out_box">
      	<h2>Rel&auml; 3</h2>
                  <form class="check_LEDs" name="LED_form5">
      		<h3>V&auml;xel 9</h3>
                      <input type="checkbox" name="LED17" value="0" onclick="GetCheck('LED17', this)" />V&auml;nster
                      <input type="checkbox" name="LED18" value="0" onclick="GetCheck('LED18', this)" />H&ouml;ger<br />
      		<h3>V&auml;xel 10</h3>
                      <input type="checkbox" name="LED19" value="0" onclick="GetCheck('LED19', this)" />V&auml;nster
                      <input type="checkbox" name="LED20" value="0" onclick="GetCheck('LED20', this)" />H&ouml;ger            
      	</form>
                  <form class="check_LEDs" name="LED_form6">
      		<h3>V&auml;xel 11</h3>
                      <input type="checkbox" name="LED21" value="0" onclick="GetCheck('LED21', this)" />V&auml;nster
                      <input type="checkbox" name="LED22" value="0" onclick="GetCheck('LED22', this)" />H&ouml;ger<br />
      		<h3>V&auml;xel 12</h3>
                      <input type="checkbox" name="LED23" value="0" onclick="GetCheck('LED23', this)" />V&auml;nster
                      <input type="checkbox" name="LED24" value="0" onclick="GetCheck('LED24', this)" />H&ouml;ger
                  </form>
              </div>
      	<div>
      	<img width="1000px" height="1000px" src=1.jpg alt="Loading..." />
      	</div>
      	</div>
          </body>
      </html>
      
      

      First One: How do I make it redirect to the second one when I input the right password?
      Second one: How do I make it redirect to the third after 3 seconds?
      Third One: How do I replace the picture at the bottom with a live stream from a local network camera?

        • Hi Oskar
          Thanks for your comments. I will email you so that you can send me your code as an attachment, which will be a bit easier to read.
          I have added a comment section below each article on the website using the Disqus commenting system which I think allows you to post an image if you are interested in using it.
          To get the code looking good in this blog commenting system I think that it must be put in between <pre> tags and all & must be converted to &amp;, < converted to &lt; and all > converted to &gt; like this:

          <!DOCTYPE html>
          <html>
              <head>
                  <title>Arduino Web Page</title>
              </head>
              <body>
                  <h1>Hello from Arduino!</h1>
                  <p>A web page from the Arduino server</p>
              </body>
          </html>
          
      • Hi Oskar
        I will answer the easiest question first – Second one:
        You can use the HTML meta refresh in the top of the validating page like so:

        <!DOCTYPE html>
        <html>
        <html lang="en">
            <head>
        	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        	<meta http-equiv="refresh" content="3; url=index3.htm" />
        	<title>Login</title>
        
        ... rest of file
        

        The 3 in the content part of the line sets it to redirect to index3.htm after 3 seconds. You can find out more here: https://en.wikipedia.org/wiki/Meta_refresh

        For your fist question – have you written the code to process the password access on the page or is that what you need to know?

        Third question – to stream video, I would look at using a PC or Raspberry PI board to stream the video and reference it as an external resource from the HTML page. You don’t want the video to be hosted by the slow Arduino server.

        • I need both the script for the input, and how to redirect when I write the correct password, and then I need the script how to embed the video that is processed by my Raspberry P.I without using my Arduino ram.

          At last I need the Arduino script to handle the pages.

          • I am busy working on a general purpose Arduino web server that will handle various file types and have password protection as one of the things to add. I can’t give you all the answers right now, but they have been added to my TODO list.

  179. HI!!!

    FIRST OF ALL I WOULD LIKE TO THANK U FOR UR HELP IN IMPLEMENTING THIS SERVER PROJECT.IT HELPED ME ALOT TO LEARN SEVERAL NEW CONCEPTS RELATED TO WEBSERVER.

    ALSO,IN THIS SERVER CAN WE MEASURE ESSENTIAL SERVER PERFORMANCE METRICS SUCH AS
    1.REQUESTS PER SECOND (RPS)
    2.AVERAGE RESPONSE TIMES (ART)
    3.PEAK RESPONSE TIMES (PRT)
    4.UPTIME
    5.CPU UTILIZATION
    6.MEMORY UTILIZATION
    7.THE COUNT OF THREADS
    8.THE COUNT OF OPEN FILES DESCRIPTORS

    WHILE SURFING INTERNET I HAVE COME ACROSS SEVERAL SOFTWARE USED FOR WEB SERVER MONITORING.SO WHAT CAN WE DO TO MEASURE ATLEAST FEW SERVER PERFORMANCE METRICS IN THIS SERVER ?

    PLZ HELP ME BY SUGGESTING SOME IDEA!!!!!!!!!!

    • Hi akipeed
      A lot of the metrics that you mention are only possible on a full web server that runs on a fast processor and on top of an operating system. The Arduino is a small embedded system with limited resources, especially when using the Uno. As far as I know, the Wiznet Ethernet chip on the Arduino Ethernet shield can only support four simultaneous connections.

      Timing metrics: You may be able to implement some of the timing metrics, but with the Arduino already using it’s processing power to handle the web server functions and other code, there is probably only enough power for very simple metrics. You can probably use the millis() function to time various events.

      Memory utilization: If you look at the web server by SurferTim called WebServerST that someone mentioned here, he added a lot of debug code to it and one of the things he was measuring was the available RAM on the system. But this web server is really intended to run on a MEGA or better and is not really intended for the Uno.

      Open file descriptors: There will only ever be one file open at a time because the Arduino code opens the file, sends the data to the browser, then closes the file and the connection to the browser (client).

      There won’t be any count of threads because the code is not multi-threaded.

        • I have some basic code together for the general purpose web server and am still busy with development.

          • i have a static ip address(port forwarded) and i need to access the web server from anywhere using internet. what should i do for that?

            does changing the LAN IP in IPAddress ip(192, 168, 0, 20); to WAN IP suffice?

            i tried that but i havent get anything in the browser?

            what can i do?

          • Hi akipeed
            You should just have to use the Arduino IP address in the port forwarding of the router. When you add the Arduino to the port forwarding, make sure that HTTP(TCP:80)is selected (or similar depending on your router).
            On my router, I just put the Arduino IP in which I usually set at 192.168.0.20, then select HTTP and Add.
            After that it is just a matter of finding out your main IP address, which will be your static IP, then surf to that address using your browser. The router will then forward the HTTP requests to the Arduino.

  180. that means,does i hve to use WAN IP in my browser to see d web page?
    does i hve to mention port no also along with ip in browser?

    • No, you can then use your static IP address whether you are on your local computer or connecting from an external network. But you should be able to use the local IP address of the Arduino on your local network as well. You only need to set the port number in your port forwarding if that is an option in your router settings.

  181. HI and thanks again for the tutorials.
    I have been using all of the lessons learned here to implement some great projects, and am learning a lot.
    I have a question that is not directly related but I couldn’t work out where else to ask.
    I have been trying to create an Arduino sports score display (LCD or whatever) in particular for Cricket scores (big following here in Australia) but any sport would be good.
    I have looked at “tickers” etc but can’t seem to find a way to make it work.
    I stumbled across a very simple js script that shows very basic summary of current games on a web page. Link and actual code at the bottom.
    I thought it should be possible to take the information received from the site and use it on an Arduino display.
    Is this something that you would be interested in?
    Any “pointers” in the right direction would be much appreciated.
    The js comes from this page “http://www.funbutlearn.com/2013/01/how-to-put-live-cricket-score-on-your.html”
    I understand most of what it does, but don’t know how to get an arduino to do it.
    code is copied here

    var ONLY_SHOW_MATCH_FOR = "";
    function getScore(data){
    	var matches = data.query.results.mchdata.match;
    	for(var i=0;i=0){
    			document.getElementById("matches").innerHTML+=""+matches[i].mchDesc+"";
    			if(isNotUndefined(matches[i].mnum)){
    				document.getElementById("matches").innerHTML+=matches[i].mnum;
    			}
    			if(isNotUndefined(matches[i].srs)){
    				document.getElementById("matches").innerHTML+=", "+matches[i].srs;
    			}
    			if(isNotUndefined(matches[i].grnd)){
    				document.getElementById("matches").innerHTML+=""+matches[i].grnd+"";
    			}
    			if(isNotUndefined(matches[i].vcity)){
    				document.getElementById("grnd"+i).innerHTML+=", "+matches[i].vcity;
    			}
    			if(isNotUndefined(matches[i].mscr) &amp;&amp; isNotUndefined(matches[i].mscr.btTm) &amp;&amp; isNotUndefined(matches[i].mscr.btTm.Inngs)){
    				document.getElementById("matches").innerHTML+="<b>"+matches[i].mscr.btTm.sName+": </b>";
    				document.getElementById("btTm"+i).innerHTML+= matches[i].mscr.btTm.Inngs.r;
    				document.getElementById("btTm"+i).innerHTML+= "/"+matches[i].mscr.btTm.Inngs.wkts;
    				document.getElementById("btTm"+i).innerHTML+= " ("+matches[i].mscr.btTm.Inngs.ovrs+")";
    			}
    			if(isNotUndefined(matches[i].mscr) &amp;&amp; isNotUndefined(matches[i].mscr.blgTm) &amp;&amp; isNotUndefined(matches[i].mscr.blgTm.Inngs)){
    				document.getElementById("matches").innerHTML+="<b>"+matches[i].mscr.blgTm.sName+": </b>";
    				document.getElementById("blgTm"+i).innerHTML+= matches[i].mscr.blgTm.Inngs.r;
    				document.getElementById("blgTm"+i).innerHTML+= "/"+matches[i].mscr.blgTm.Inngs.wkts;
    				document.getElementById("blgTm"+i).innerHTML+= " ("+matches[i].mscr.blgTm.Inngs.ovrs+")";
    			}
    			if(isNotUndefined(matches[i].state) &amp;&amp; isNotUndefined(matches[i].state.status)){
    				document.getElementById("matches").innerHTML+=""+matches[i].state.status+"";
    			}
    			document.getElementById("matches").innerHTML+="<a href='http://www.cricbuzz.com/cricket-match/live-scores' rel="nofollow">See details</a>";
    			document.getElementById("matches").innerHTML+="";
    		}
    	}
    }
    function isNotUndefined(val){
    	if(val!=undefined &amp;&amp; val!=null)
    		return true;
    	else
    		return false;
    }
    
    • Hi John
      The proper way to get the scores to the Arduino would be to operate the Arduino as an Ethernet client instead of an Ethernet server.

      If you run the Arduino as an Ethernet server, then it would need to host a web page that contains the JavaScript code. The problem with this is that the JavaScript code gets loaded to the web browser and when the JavaScript runs from the web browser, it fetches the cricket score. This bypasses the Arduino.

      The solution is to program the Arduino to be a client that does what the JavaScript is doing. The Arduino can then fetch the cricket score itself, then you can display the score on the LCD or other display.

      I can look at doing a tutorial for this if you need some more help.

      • Hi
        Thanks for the fast answer.
        If you think a tutorial is worth your effort and of interest to others, I would love it!
        I agree with you about using the Arduino as a client, and realised the same thing after experimenting some more. I have managed to get a YQL response and was trying to work out how to get only the relevant data out, perhaps “jsonFilter” using the ajson arduino library, or “indexOf ()”.
        Anyway, I find YQL stops responding after a few requests, and does not respond again until a day later. I was careful to send the request only 1 time in setup(), so it would not exceed the YQL rate limit. I don’t know why it works for a short time then stops responding.
        I can post or send the code I have so far, but as it is reasonably large I did not want to post it here.

        Thanks again, and if it works out, looking forward to the tutorial.

        Kind regards
        John

        • Hi John
          I will start doing some development this week and hopefully get a tutorial out some time next week.

        • Hi John
          I have got some basic code working that is getting the cricket scores and displaying them in the Serial Monitor window of the Arduino IDE. At the moment the score is only fetched once which happens when the Arduino is reset at the time that the Serial Monitor window is opened.

          I want to change the code to update the score every 15 seconds or so before publishing the code and tutorial. Will keep you posted.

          • Brilliant..
            I have been trying to get something working here using the arduinojson library but I still can’t seem to extract the info I want. Same as you also via the serial monitor for now. I just get parse errors..
            Big game starts this week so your timing is perfect. 🙂
            Can’t wait to see what the heck I am doing wrong.
            Thanks again,
            Everyone, make sure you donate something to keep this fantastic resource alive.

            Cheers John

        • Hi John
          I have published the the Arduino cricket score project here: http://startingelectronics.org/software/arduino/live-cricket-score/

          To comment on the project on this blog, go here: http://blog.startingelectronics.com/using-arduino-as-a-sports-score-ticker-to-get-live-cricket-results/

          The code does have some limitations and could encounter some problems as noted in the article. I intend to write an improved version of the code that is more robust and can handle errors and unexpected data.

  182. HI!!!!!!!

    how is ur general purpose web server design and development?
    have u completed?
    i am eagerly looking forward for this project!!!!
    plz reply!!!!!!!!!

    • Hi akipeed
      I have made the first of a series of web servers and will be publishing it soon. The first web server is a basic server that will host several different file types that are stored on the SD card. The idea behind this first web server is to make the code easy to understand, and so has less features. Later web servers will improve on the basic web server with additional security and features.
      I also have in mind to make some software tools that will make Arduino web server projects easier to develop.

      • Thanks for ur reply!!!!!!!!!!!

        when i reported this web server to my prof. he asked me several doubts.After hearing that i am also confused a little bit.The doubts are

        1.what is the difference between general web server and arduino web server?
        2.what is the use of arduino web server?
        3.does arduino web server can host websites?
        4.if arduino web server able to host websites then how many users it can support and what is its speed?

        i am eagerly waiting for ur first web server design,i request u to publish it within this week.Because it will be very useful for my project which is to be held on next month.

  183. when i reported ur old ethernet web server to my prof. he asked me several doubts regarding project.
    After hearing that i am also confused a little bit.The doubts are

    1.does arduino web server can host websites?
    2.if arduino web server able to host websites then how many users it can support and what is its speed?
    3.what is the difference between general web server and arduino web server?
    4.what is the use of arduino web server?

    can u guide me to figure out these doubts?

    • Hi akipeed
      Answers to your questions:
      1. The Arduino web server can host a website, but remember that it is a small embedded system so has limits. It can’t be compared to a full blown web server such as Apache or Nginx.

      2. The Wiznet Ethernet chip found on the Arduino Ethernet shield has a limitation of 4 simultaneous sockets, which translates to a maximum of 4 simultaneous connections (info and data sheet: http://www.wiznet.co.kr/product-item/w5100/). The speed of the web server is limited by the time that it takes to get web resources (pages, images, CSS files, etc.) from the SD card and send them to the client. The smaller the web pages and other resources, the faster the web server will be.

      3. If I understand correctly, you are referring to the new web server code and the code from the Arduino Ethernet shield tutorial. Remember that the tutorial is for explaining concepts and technology and uses hard-coded web pages. The general purpose web server handles files with any names as well as different file types. The tutorial is there so that you can learn and then make your own web server. The general purpose web server is a complete web server that can host several different file types, but has some limitations that are documented.

      4. Again if you are referring to the web server from the tutorial, it is for teaching and demonstrating how to display and control Arduino I/O from a web page while at the same time keeping the code simple for learning. The general purpose web server does not include any I/O examples as this will be custom code that you can add for your specific project which you will learn how to do from the tutorial.

  184. 1.That means the old web server code(not a new one) which supports monitoring and controlling LEDs,Switches is meant for Internet of Things (IoT) purpose?

    2.Also i tried to interface LCD with old code but it doesnt work properly,i think since it is single threaded as u said in a forum,it doesnt interface LCD properly as it will become multithreading.am i right?

    3.Also, can i include ur new web server code which supports all file types to old one?

    PLZ REPLY TO THIS SO MANY QUESTIONS ARE BOMBARDING MY HEAD!!!!!!!!!

    • Hi akipeed
      1. You can call it a Internet of Things application, but the main purpose is that it is a tutorial. There will be another web server coming up that will be like the general purpose web server, but also allow monitoring and controlling.

      2. The LCD should work, if you are running the code on an Arduino Uno there is a possibility that you have run out of memory. You also need to write your code so that it does not block any code that needs to run — for example if the code spends time waiting for something when it could be doing another task.

      3. You should be able to add the Ajax I/O code to the new web server.

      • THANKS FOR UR REPLY!!!!!!!!!!

        feeling good to hear news abt general purpose web server.i am eagerly waiting for ur general purpose web server design.

        what is the TCP/IP stack used in this project?

          • Again thank u so much!!!!

            1.what are the client side scripting and server side scripting used in webserver tutorial?

            2.how can i monitor http communication?
            is there any software to monitor http communication between server and client?

          • Hi akipeed
            1) The client side scripting language is JavaScript. The server side language is the Arduino language which is basically C / C++ so it is not actually a scripting language, but a compiled language.

            2) I use a browser add-on for the Firefox web browser called HttpFox to monitor HTTP communications. The only problem with HttpFox is that it was made to display on some toolbar or other widget that no longer exists in the newer versions of Firefox, so it can’t be opened using a mouse click. The trick is to use the keyboard shortcut to start HttpFox which is Ctrl + Shift + F2. You will need to first install HttpFox from the Firefox Add-ons menu. Another tool is Wireshark, but it will also display all the underlying protocols and not just the HTTP.

  185. Hi,
    My project consists of Arduino Mega 2560, Ethernet shield, SD card, servos, etc…

    I’ve hosted a html page on the SD card,the html consists of checkboxes and dropdown lists.

    1) how do I pass the value that was selected on the dropdown list to arduino? eg. there are 2 dropdown list: 1 for hour and 1 for minute. When user selects hour: 10 minute: 00, value will be sent to arduino and schedule is set at 10:00.

    2) there are total of 3 html page. how do I redirect from page 2 to page 3? noticed that from index.htm, im able to direct to page2.htm but from page2.htm, when I redirect to page3.html, the url shows %22page3.html%22 and it displays a blank page.

    • Hi Eva
      1) You will need to get the value from the drop-down list using JavaScript and then pass it to the Arduino the same way that checkbox data is sent.

      2) The tutorial is not a complete web server, but teaches web principles and technology. The examples that link pages to each other look for hard-coded page names. To link to any page irrespective of name, take a look at the web server code here: http://startingelectronics.org/software/arduino/web-server/basic-01/

      • Hi,

        Thanks for your reply. I manage to solve the redirection using part 10 arduino sd web server example.

        For question 1, do you have any example that I could follow? This is my first project using arduino, HTML .

        Thanks!

          • Hi,

            On my html page, after selecting checkbox1 and set hour:11 Minute:00, noticed in the serial monitor that it shows &checkbox1=11100.
            May I know how to split the hour and minute and store it into an array for arduino?

            Thanks!

          • Hi,
            Did you manage to create a tutorial on get values from HTML to arduino using JavaScript ?

            Another question, after I select the hour and minute from index.html, when I navigate to page2.html, the schedule does not work. May I know what should I do so that no matter what page I click the schedule will still function?

          • Hi Eva
            I have not had a chance to write the new tutorial, but it is on my list of things to do.

            I’m not too sure what you mean by schedule. Is this a timing function on the Arduino that uses the hour and minute sent from the web page?

          • Hi,
            I’ve got an RTC that is connected to my arduino. Once I select the hour and minute from the webpage, arduino would use the strcontains function to get the hour and minute from serial monitor and pass in the value to another function whereby if the time = current time, alarm would ring.
            Below is my code for RTCtime and printtime

            void RTCtime() {    
               // send request to receive data starting at register 0
              Wire.beginTransmission(0x68); // 0x68 is DS3231 device address
              Wire.write((byte)0); // start at register 0
              Wire.endTransmission();
              Wire.requestFrom(0x68, 3); // request three bytes (seconds, minutes, hours)
             
              while(Wire.available())
              { 
                seconds = Wire.read(); // get seconds
                minutes = Wire.read(); // get minutes
                hours = Wire.read();   // get hours
             
                seconds = (((seconds & 0b11110000)>>4)*10 + (seconds & 0b00001111)); // convert BCD to decimal
                minutes = (((minutes & 0b11110000)>>4)*10 + (minutes & 0b00001111)); // convert BCD to decimal
                hours = (((hours & 0b00100000)>>5)*20 + ((hours & 0b00010000)>>4)*10 + (hours & 0b00001111)); // convert BCD to decimal (assume 24 hour mode)
              }
            }
            
            void printTime(){   //Print time to the LCD
              lcd.setCursor(0,1);
              char time[17];
              sprintf(time, "    %02i:%02i:%02i", hours, minutes, seconds);
              lcd.print(time);
            }
          • If you are just getting the alarm time from the web page, then make sure that you store it locally on the Arduino. The code that compares the current time with the alarm time must not sit in a loop or if statement that relies on the Ethernet connection so that it will not be blocked if you disconnect from the server or load a different web page.

          • Hi,

            I did store the alarm time from the webpage in an array in arduino. I used the following tutorial :Arduino SD Card Web Server – Linking Pages. Could you tell me the function which compares the current time with the alarm time should be placed under which section based on the code you have in Arduino SD Card Web Server – Linking Pages?

          • Hi Eva
            I would think that it should go outside the the main block that checks for a client and then servers up the web page which is outside this if statement block:

            if (client) {
          • Hi,

            Thanks very much. I manage to get it to work. An issue occurred is that Chronodot rtc timer is connected to arduino. Previously, the time shown on the lcd screen is correct however now the difference between the actual time and time displayed on the lcd is 30mins. May I know how to reconfigure or reset the time to the same as the actual time?

      • Hi,

        Thanks. I will look at the tutorial. I’m thinking of logging this. Example, when alarm time is up, if the pressure sensor detects that the candy is removed it will log down as Yes in the candy taken column. The log format will be date column, time column and candy
        taken column. Arduino will write logs to the sd card and on the web page I want to display the logs that arduino has written to sd card.

        I urgently need your suggestion on the following issue. My current design: hosted webpage on sd card on ethernet shield. Arduino mega is connected to the ethernet shield and lcd shield. Ethernet shield is connected to the modem via ethernet cable . The issue is my prof want the connection between arduino to the modem wireless. How can this be achieve? Objective is there will be a base unit and dispensing unit. Base unit can be the PC and the dispensing unit will be the arduino. Base unit needs to be able to connect multiple dispensing unit wirelessly. Meaning on base unit I will be able to select which dispensing unit I want to schedule the alarm.

        • To get a wireless connection to the modem should just be a matter of replacing the Ethernet shield with a WiFi shield, assuming that the modem has built-in WiFi. I haven’t tested the WiFi shield myself and they are pretty expensive. For half the price of a WiFi shield you can buy a Raspberry PI board and USB WiFi dongle. There are some cheaper Arduino compatible WiFi shields.

          • Hi,

            The wifi shield is really very costly. Do you think instead of getting a wifi shield, I can get a wireless router ( TP Link:TP-WR702N)to connect to the ethernet shield?

          • I had a look at the router spec. and it looks like it should work. My only concern is that they show it connected to a PC via USB. I assume that the “bridge” mode would let you connect between the wired Ethernet and WiFi, but you will need to check this.

          • Hi,

            Thanks alot for your help. Just wondering how could i connect multiple dispensing unit to the base unit?

            Base unit: PC
            Dispensing Unit: arduino mega, ethernet shield, TP-link wireless router, sensors, servos, etc…

          • Hi Eva
            I don’t have a clear picture of what you are trying to do. Are your dispensing units set up as Arduino web servers? Do you access each dispensing unit from a browser on the PC base unit? Or if not, what must the base unit do?

          • Hi,

            Currently I’m hosting the website on the dispensing unit. Yes, the dispensing unit is also an arduino webserver.To schedule the dispensing time, I will access via web browser on the base unit pc.

          • Then to connect the multiple dispensing units to the base unit would mean that you just need to have them on the same network, each with it’s own IP address. You then access each web server from the base unit at it’s IP address.

    • Hi akipeed

      1) Ajax is a technique that uses JavaScript and a server side language for passing data between client and sever and vice versa.

      2) You will see the MIME types for the different types of files in the file_types array in the web server code here:
      http://startingelectronics.org/software/arduino/web-server/basic-01/

      3) I have not looked into DHCP and DNS. There are some DHCP examples in the Arduino IDE examples under the Ethernet menu. Just remember that the Arduino Uno has limited resources, so if you want to add too much functionality you may need to move to a MEGA or other bigger Arduino.

      4) There is no official RTOS for Arduino at this stage, but doing a search for “Arduino RTOS” brings up several projects.

      5) I have not looked at Webduino yet, but thanks for the link I will take a look.

  186. Hi,

    1) Based on example on Part 13: Arduino SD Card Ajax Web Server, if it’s a dropdown list instead of a button on the html page, how do i pass the selected value to arduino?

    2) Based on example on Part 10: Arduino SD Card Web Server – Linking Pages , my webpage consists of a menu bar with 4 tabs. I’m able to navigate from page1 to page2 but unable to navigate from page2 to page3. When i navigate from page2 to page3, the url changes to %22page3.htm%22. May I know what changes is to be done?

    Thanks!

  187. HI!!!!!
    I NEED UR SUGGESTION FOR MY PROJECT THAT

    1.Is it possible to host a website using embedded web server(using microcontroller)?
    2.what will be the constraints and limitations in implementing the project?
    3.what will be the requirements for the project?

    plz reply it will be helpful for my project review!

    • Hi akipeed
      1) Yes it is possible to host a website, but if you are referring to hosing a website like you would do by buying a web hosting package then it is not practical.

      2) The Arduino can only handle four simultaneous connections and has limited speed, memory and bandwidth. Even if you were hosting your own website on a PC at home, there will be limitations from your Internet service provider on your ISP package. Most ISP web access is intended for web access and not hosting, so download speeds are faster than upload speeds. There are other packages that may be called “business” packages that will have been designed to enable better self-hosting. Of course here I am referring to using a PC as the web host and not the Arduino. The Arduino resources are so limited that you could probably use an Arduino web server on any ISP package, upgrading to a business package would not serve any purpose for the Arduino because it would never even use all the resources of a home package.

      3) For a web server you need as little as an Arduino Uno and Ethernet shield, or Arduino Ethernet board. It depends on your project specification. What do you want to use the Arduino web server for?

  188. I’m using chronodot from this website:
    http://docs.macetech.com/doku.php/chronodot_v2.0
    Noticed in the code that there is a section to clear /EOSC bit. Not sure if my understanding is correct , the clearing of the /EOSC should reset to the correct time?

    Another question, do you have a tutorial for arduino to write logs to SD card and from website (html hosted on SD) read the logs and display on the website in table form?

    • Clearing a bit to set the correct time does not sound right. You should have to write the time to various registers to set it properly, e.g. hour register, minute register, etc.

      I don’t have a tutorial on logging at the moment. What do you want to log?
      There is a Datalogger example in the IDE under File –> Examples –> SD –> Datalogger
      I am sure someone has asked for this before. I want to extend the web server tutorials and add an example that includes logging and displaying the info on a page. I will try to get this done as soon as possible, but can’t promise when.

  189. Pingback: Arduino Web Server Tutorial | CareWare

  190. Hi,

    Thanks. I will try it out.

    Another question i have is on my webpage i need to add a “Save” button and a “Reset” button.
    The “Save” button is to save the settings (example: time) that i set on the webpage. For example, i would set the time and click save and I would navigate to another tab .When i return to the settings page, I should get the settings that i previously saved.
    The purpose of the reset button is, once clicked, the settings should reset to the default settings.

    May I know how can this be done?
    I’ve researched and came across this link:
    http://www.howtocreate.co.uk/tutorials/jsexamples/saveForm.html
    It is exactly what i needed but i do not know how to incorporate into my code. Please advice if there is any simpler way of implementing.

    Thanks

    • I mange to get the reset button working. For the save button I manage to get only half of it working. How to get the value of a checkbox to see if it is checked or unchecked?

      • Take a look at the parts of the tutorial series that use checkboxes, for example switching an LED on with a checkbox.

  191. Thank you for the lessons on the Arduino Web Server.
    I think these are the best lessons on the internet.
    Thank you for making it easy to understand.
    I like these lessons very much.
    Forever grateful…
    Acutus
    10-14-2015

  192. Hi, thank you so much for all the work you have put into these tutorials, in a very short time I have gone from knowing nothing about coding or html to been able to integrate several of your examples into a fully working project.

    I trying to tweak a couple of things at the moment, one of which is to adapt the code to turn on a led or relay by clicking and holding a html button, is this possible???

    Also do you know how I can adapt the js code for the gauges to display a 360 degree guage ( for example to display wind direction for a weather station)

    Thanks in advance, and again the tutorials are awesome

    Tom

    • Hi Tom
      Glad to hear that you have enjoyed the articles. I’m not sure about clicking and holding an HTML button, I am guessing that you could do something like that with JavaScript. For a 360 degree gauge I would personally write something from scratch rather than adapt the existing code. I don’t have time to look into this at the moment, but if you don’t have any success, then drop me a note and I will see what I can do when I have some more time.

  193. Hi, me again!!

    I have brought together a lot of your examples into one sketch where I can now control multiple LEDs and display various analog values to gauges running on 2 different web pages hosted on the SD card on the Ethernet shield; with everything working as is should.

    But I am now trying to also read gps (nmea) data using tinygpsplus. The problem is that although I am receiving the data I am struggling to get the webpage where the text is displayed to update. It seems to have a mind of it own when updating, sometimes every few seconds and then no update for a minute.

    I think the problem might lie in that I’m sending data from the void XML_response rather than from the void loop in the first if statement, (please see code attached). I’ve tried cl.print from here but getting an error “not declared in this scope”. Any ideas??

    Thanks in advance

    #include //
    #include //
    #include
    #include
    #include
    // size of buffer used to capture HTTP requests
    #define REQ_BUF_SZ 120
    #define NUM_SAMPLES 10 //for voltage

    static const int RXPin = 13, TXPin = 51; //
    static const uint32_t GPSBaud = 4800;

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin,true); //

    // MAC address from Ethernet shield sticker under board
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 0, 3); // IP address, may need to change depending on network
    EthernetServer server(80); // create a server at port 80
    File webFile; // the web page file on the SD card
    char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
    char req_index = 0; // index into HTTP_req buffer
    boolean LED_state[4] = {0}; // stores the states of the LEDs (or relays)

    volatile byte rpmcount; //variables
    unsigned int rpm;
    unsigned long timeold;
    int sum = 0;
    unsigned char sample_count = 0;
    float voltage = 0.0;

    TinyGPSCustom latitude(gps, “GPGGA”, 2); // $GPGSA sentence, 2th element
    TinyGPSCustom NS(gps, “GPGGA”, 3); // $GPGSA sentence, 3th element
    TinyGPSCustom longitude(gps, “GPGGA”, 4); // $GPGSA sentence, 4th element
    TinyGPSCustom EW(gps, “GPGGA”, 5); // $GPGSA sentence, 5th element

    void setup()
    {

    //for rpm
    attachInterrupt(0, rpm_fun, FALLING);
    digitalWrite(2, HIGH);

    rpmcount = 0;
    rpm = 0;
    timeold = 0;

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

    Serial.begin(9600); // for debugging
    ss.begin(GPSBaud); // listen for NMEA

    // 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.”);
    // switches on pins 3 and 5
    //pinMode(3, INPUT);
    //pinMode(5, INPUT);

    // LEDs/relays
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(22, OUTPUT);

    Ethernet.begin(mac, ip); // initialize Ethernet device
    server.begin(); // start to listen for clients
    }

    void loop()
    {

    if (
    latitude.isUpdated() || NS.isUpdated() || longitude.isUpdated() || EW.isUpdated())
    {
    //Serial.print(F(“LAT=”)); Serial.print(gps.location.rawLat().deg);
    // Serial.print(“LAT=”);
    //client.print(“”);
    // cl.print(latitude.value());
    //cl.println(“”);

    //Serial.print(F(” “));
    // Serial.println(NS.value());
    //Serial.print(F(“LONG=”));
    //Serial.print(longitude.value());
    //Serial.print(F(” “));
    //Serial.println(EW.value());

    }

    while (ss.available() > 0) //
    gps.encode(ss.read()); //

    if (analogRead(8)<600) {
    digitalWrite(22, HIGH);
    }
    else {
    digitalWrite(22, LOW);
    }

    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
    // limit the size of the stored received HTTP request
    // 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.print(c); // print HTTP request character to serial monitor **
    // 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");
    // remainder of header follows below, depending on if
    // web page or XML page is requested
    // Ajax request – send XML file
    if (StrContains(HTTP_req, "ajax_inputs")) {
    // send rest of HTTP header
    client.println("Content-Type: text/xml");
    client.println("Connection: keep-alive");
    client.println();
    SetLEDs();
    // send XML file containing input states
    XML_response(client);
    }
    else { // web page request
    // send rest of HTTP header
    client.println("Content-Type: text/html");
    client.println("Connection: keep-alive");
    client.println();
    // send web page
    //**webFile = SD.open("index.htm"); // open web page file
    if (StrContains(HTTP_req, "GET / ")
    || StrContains(HTTP_req, "GET /index.htm")) {
    webFile = SD.open("index.htm"); // open web page file
    }
    else if (StrContains(HTTP_req, "GET /page1.htm")) {
    webFile = SD.open("page1.htm"); // open web page file
    }
    else if (StrContains(HTTP_req, "GET /page2.htm")) {
    webFile = SD.open("page2.htm"); // open web page file
    }
    if (webFile) {
    while(webFile.available()) {
    client.write(webFile.read()); // send web page to client
    }
    webFile.close();
    }
    }
    // display received HTTP request on serial port
    Serial.print(HTTP_req);
    // 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)

    //Update RPM every second ***this was (1000) but was causing the switchs to not respond quickly or at all**
    //delay(200); //decides to take out delay, dosn't seem to cause any issues
    //Don't process interrupts during calculations
    detachInterrupt(0);
    //Note that this would be 60*1000/(millis() – timeold)*rpmcount if the interrupt
    //happened once per revolution instead of twice. Other multiples could be used
    //for multi-bladed propellers or fans
    rpm = 30*1000/(millis() – timeold)*rpmcount;
    timeold = millis();
    rpmcount = 0;

    //Restart the interrupt processing
    attachInterrupt(0, rpm_fun, FALLING);

    while (sample_count< NUM_SAMPLES){
    sum+= analogRead(A14);
    sample_count++;
    delay(10);
    }

    voltage = (((float)sum / (float)NUM_SAMPLES*4.83)/1023.0)*5.830; //to measure voltage with voltage divider, will need calibration is diiferent Resistors are used.

    sample_count=0;
    sum=0;

    }

    // checks if received HTTP request is switching on/off LEDs
    // also saves the state of the LEDs
    void SetLEDs(void)
    {
    // LED 1 (pin 6)
    if (StrContains(HTTP_req, "LED1=1")) {
    LED_state[0] = 1; // save LED state
    digitalWrite(6, HIGH);
    }
    else if (StrContains(HTTP_req, "LED1=0")) {
    LED_state[0] = 0; // save LED state
    digitalWrite(6, LOW);
    }
    // LED 2 (pin 7)
    if (StrContains(HTTP_req, "LED2=1")) {
    LED_state[1] = 1; // save LED state
    digitalWrite(7, HIGH);
    }
    else if (StrContains(HTTP_req, "LED2=0")) {
    LED_state[1] = 0; // save LED state
    digitalWrite(7, LOW);
    }
    // LED 3 (pin 8)
    if (StrContains(HTTP_req, "LED3=1")) {
    LED_state[2] = 1; // save LED state
    digitalWrite(8, HIGH);
    }
    else if (StrContains(HTTP_req, "LED3=0")) {
    LED_state[2] = 0; // save LED state
    digitalWrite(8, LOW);
    }
    // LED 4 (pin 9)
    if (StrContains(HTTP_req, "LED4=1")) {
    LED_state[3] = 1; // save LED state
    digitalWrite(9, HIGH);
    }
    else if (StrContains(HTTP_req, "LED4=0")) {
    LED_state[3] = 0; // save LED state
    digitalWrite(9, LOW);
    }
    }

    // send the XML file with analog values, switch status, warning light status
    // and LED status
    void XML_response(EthernetClient cl)
    {
    int analog_val; // stores value read from analog inputs
    int analog_val_2;
    int analog_val_3;
    float analog_val_4;
    int analog_val_5;

    //int count; // used by 'for' loops
    //int sw_arr[] = {3, 5}; // pins interfaced to switches

    cl.print("”); //sends data to webpage is for Gauge script
    cl.print(“”);

    analog_val = analogRead(8); //Oil Pressure
    cl.print(“”);
    cl.print(analog_val);
    cl.println(“”);

    analog_val_2 = analogRead(15); //Water Temp
    cl.print(“”);
    cl.print(analog_val_2);
    cl.print(“”);

    analog_val_3 = rpm; //Tacho
    cl.print(“”);
    cl.print(analog_val_3);
    cl.print(“”);

    analog_val_4 = voltage; //Engine Battery
    cl.print(“”);
    cl.print(voltage);
    cl.print(“”);

    analog_val_5 = analogRead(9); // is for Gauge2 script, ie Rudder Indicator
    cl.print(“”);
    cl.print(analog_val_5);
    cl.print(“”);

    // read switches – not currently connencted, could be used for doors/valves open etc
    //for (count = 0; count < 3; count++) {
    // cl.print("”);
    // if (digitalRead(sw_arr[count])) {
    // cl.print(“ON”);
    // }
    // else {
    // cl.print(“OFF”);
    // }
    // cl.println(“”);
    // }

    // button LED states
    // LED1
    cl.print(“”);
    if (LED_state[0]) {
    cl.print(“on”);
    }
    else {
    cl.print(“off”);
    }
    cl.println(“”);
    // LED2
    cl.print(“”);
    if (LED_state[1]) {
    cl.print(“on”);
    }
    else {
    cl.print(“off”);
    }
    cl.println(“”);
    // LED3
    cl.print(“”);
    if (LED_state[2]) {
    cl.print(“on”);
    }
    else {
    cl.print(“off”);
    }
    cl.println(“”);
    // LED4
    cl.print(“”);
    if (LED_state[3]) {
    cl.print(“on”);
    }
    else {
    cl.print(“off”);
    }
    cl.println(“”);

    // Warning Lights – only Oil Pressure shown – add more as required

    //Oil Pressure
    cl.print(“”);
    if (analogRead(8)<600) {
    cl.print("on");
    //digitalWrite(22, HIGH);
    }
    else {
    cl.print("off");
    //digitalWrite(22, LOW);
    }
    cl.println("”);

    cl.print(“”);
    cl.print(latitude.value());
    cl.println(“”);

    cl.print(“”);
    }

    // sets every element of str to 0 (clears array)
    void StrClear(char *str, char length)
    {
    for (int i = 0; i len) {
    return 0;
    }
    while (index < len) {
    if (str[index] == sfind[found]) {
    found++;
    if (strlen(sfind) == found) {
    return 1;
    }
    }
    else {
    found = 0;
    }
    index++;
    }

    return 0;
    }

    //Part of the RPM code – not sure why its down here but it works
    void rpm_fun()
    {
    //Each rotation, this interrupt function is run twice, so take that into consideration for
    //calculating RPM
    //Update count
    rpmcount++;
    }

    • Hi again. Extremely busy at the moment. Will take a look when I get a chance.
      Thanks for the donation by the way 🙂

  194. Hi, I have solved the problem I was having above by removing two delay functions in the code. Is there a simple piece of code I can just insert in place of: for example delay(1)??

    I have read about Blink without delay but Im struggling to get my head around it.

    One other problem also!!! in javascript, I am receiving a variable(nmea) from the ardunio, its sending via xml either the letter E or W.

    I need to write a function to give another variable within the script a value of -1 when variable(nmea) is W.

    could you write an example, Im just not getting it.

    Thanks very much

  195. Hello
    First I want to thank you for this great tutorial.
    my problem is that I test the Part 16 it work fine but when I change a little the html strucute the broswer update the page but nothing work when I click the buttons it seems like a request problem

    waite for your help and thank you again 🙂
    —————————–
    sorry for my poor English.

  196. Hi
    I want to control pwm LED lights through the web page by using the slider, but I do not know how it functions in arduino sketch and html. Can you guide me?

Leave a Reply

Your email address will not be published. Required fields are marked *