Excellent Arduino Ethernet Shield Web Server Tutorial

You need to replace this with your web page.

          client.println(F("<head><script type=\"text/javascript\">"));
          client.println(F("function show_alert() {alert(\"This is an alert\");}"));
          client.println(F("</script></head>"));
          client.println(F("<body><H1>TEST</H1>"));
          client.println(F("<form method=GET onSubmit=\"show_alert()\">T: <input type=text name=t>
"));
          client.println(F("R: <input type=text name=r>
<input type=submit></form>"));
          client.println(F("</body></html>"));

Then search the request for your variables when it is submitted like mine does for "r" and "t".

oric_dan:
If you mean Part 5 of this tutorial, you will notice [as I mentioned a few posts ago], his elements are wrong. He needs either a or " />" to close them, and make them correct [at least I think so].

LED Control with Arduino Ethernet Shield Web Server

Actually, Dan, the code is perfectly valid HTML -- <input ...> is one of those tags that do not require a closing tag, usually called "self-closing tags" or sometimes "unpaired tags" or even "void elements" (<img ...> being another common one).

Have a google!

SurferTim:
Then search the request for your variables when it is submitted like mine does for "r" and "t".

My question is exactly this, because I do not understanding how can I do to become more or less this:

void ProcessButton(EthernetClient cl)
{
if (HTTP_req.indexOf("luz=Quarto") > 0)
{
if (digitalRead(4) == LOW)
{
digitalWrite(4, HIGH);
}
else
{
digitalWrite(4, LOW);
}
}

if (HTTP_req.indexOf("luz=Sala") > 0)
{
if (digitalRead(5) == LOW)
{
digitalWrite(5, HIGH);
}
else
{
digitalWrite(5, LOW);
}
}

cl.println F("<input type=\"submit\" value=\"Quarto\" onclick=\"submit();\" name=\"luz\" style=\"height:300px; width:300px; font-size:50px\">");
cl.println F("<input type=\"submit\" value=\"Sala\" onclick=\"submit();\" name=\"luz\" style=\"height:300px; width:300px; font-size:50px\">");
}

Is "HTTP_req" a String type? If so, I can't help you. zoomkat says that data type works ok, but I have not found that to be correct. Just my experience.

SurferTim:
Is "HTTP_req" a String type? If so, I can't help you. zoomkat says that data type works ok, but I have not found that to be correct. Just my experience.

"HTTP_req" is a String, but no need to use it, I just need to understand how do I read the GET requests in the code you indicated.

The request "luz=Quarto" should do this:

if (digitalRead(4) == LOW)
{
digitalWrite(4, HIGH);
}
else
{
digitalWrite(4, LOW);
}

And the request "luz=Sala" should do this:

if (digitalRead(5) == LOW)
{
digitalWrite(5, HIGH);
}
else
{
digitalWrite(5, LOW);
}

pico:

oric_dan:
If you mean Part 5 of this tutorial, you will notice [as I mentioned a few posts ago], his elements are wrong. He needs either a or " />" to close them, and make them correct [at least I think so].

LED Control with Arduino Ethernet Shield Web Server

Actually, Dan, the code is perfectly valid HTML -- <input ...> is one of those tags that do not require a closing tag, usually called "self-closing tags" or sometimes "unpaired tags" or even "void elements" (<img ...> being another common one).

Have a google!

Sheesh, too many darn rules and exceptions. I am pretty sure that adding " />" is what fixed my problem with there being interactions between buttons when I had multiple buttons, but maybe it was something else again. Will have to test it some more later - am out of town now.

Simple server test code for turning an arduino pin high/low via a web page.

//zoomkat 12-8-11
//simple button GET with iframe code
//for use with IDE 1.0
//open serial monitor to see what the arduino receives
//use the \ slash to escape the " in the html (or use ')
//address will look like http://192.168.1.102:84 when submited
//for use with W5100 based ethernet shields

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

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

String readString; 

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

void setup(){

  pinMode(5, OUTPUT); //pin selected to control
  //start Ethernet
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();

  //enable serial data print 
  Serial.begin(9600); 
  Serial.println("server LED test 1.0"); // so I can keep track of what is loaded
}

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

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

          //store characters to string 
          readString += c; 
          //Serial.print(c);
        } 

        //if HTTP request has ended
        if (c == '\n') {

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

          //now output HTML data header
             if(readString.indexOf('?') >=0) { //don't send new page
               client.println("HTTP/1.1 204 Zoomkat");
               client.println();
               client.println();  
             }
             else {
          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();

          client.println("<HTML>");
          client.println("<HEAD>");
          client.println("<TITLE>Arduino GET test page</TITLE>");
          client.println("</HEAD>");
          client.println("<BODY>");

          client.println("<H1>Zoomkat's simple Arduino button</H1>");
          
          client.println("<a href=\"/?on\" target=\"inlineframe\">ON</a>"); 
          client.println("<a href=\"/?off\" target=\"inlineframe\">OFF</a>"); 

          //client.println("<IFRAME name=inlineframe src=\"res://D:/WINDOWS/dnserror.htm\" width=1 height=1\">");
          client.println("<IFRAME name=inlineframe style=\"display:none\" >");          
          client.println("</IFRAME>");

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

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

          ///////////////////// control arduino pin
          if(readString.indexOf("on") >0)//checks for on
          {
            digitalWrite(5, HIGH);    // set pin 4 high
            Serial.println("Led On");
          }
          if(readString.indexOf("off") >0)//checks for off
          {
            digitalWrite(5, LOW);    // set pin 4 low
            Serial.println("Led Off");
          }
          //clearing string for next read
          readString="";

        }
      }
    }
  }
}

zoomkat:
Simple server test code for turning an arduino pin high/low via a web page.

//zoomkat 12-8-11

//simple button GET with iframe code
//for use with IDE 1.0
//open serial monitor to see what the arduino receives
//use the \ slash to escape the " in the html (or use ')
//address will look like http://192.168.1.102:84 when submited
//for use with W5100 based ethernet shields

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

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

String readString;

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

void setup(){

pinMode(5, OUTPUT); //pin selected to control
 //start Ethernet
 Ethernet.begin(mac, ip, gateway, subnet);
 server.begin();

//enable serial data print
 Serial.begin(9600);
 Serial.println("server LED test 1.0"); // so I can keep track of what is loaded
}

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

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

//store characters to string
         readString += c;
         //Serial.print(c);
       }

//if HTTP request has ended
       if (c == '\n') {

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

//now output HTML data header
            if(readString.indexOf('?') >=0) { //don't send new page
              client.println("HTTP/1.1 204 Zoomkat");
              client.println();
              client.println();  
            }
            else {
         client.println("HTTP/1.1 200 OK"); //send new page
         client.println("Content-Type: text/html");
         client.println();

client.println("");
         client.println("");
         client.println("Arduino GET test page");
         client.println("");
         client.println("");

client.println("

Zoomkat's simple Arduino button

");
         
         client.println("<a href="/?on" target="inlineframe">ON");
         client.println("<a href="/?off" target="inlineframe">OFF");

//client.println("<IFRAME name=inlineframe src="res://D:/WINDOWS/dnserror.htm" width=1 height=1">");
         client.println("<IFRAME name=inlineframe style="display:none" >");          
         client.println("");

client.println("");
         client.println("");
            }

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

///////////////////// control arduino pin
         if(readString.indexOf("on") >0)//checks for on
         {
           digitalWrite(5, HIGH);    // set pin 4 high
           Serial.println("Led On");
         }
         if(readString.indexOf("off") >0)//checks for off
         {
           digitalWrite(5, LOW);    // set pin 4 low
           Serial.println("Led Off");
         }
         //clearing string for next read
         readString="";

}
     }
   }
 }
}

I adapted your code with the code that I already use of sockets commands, but want to know if will still work the commands that use the socket connection made by my applications:

...

void loop() {
      
      EthernetClient client = server.available();
    
     // SE receber um caracter...
        
      delay(50); 
      if (client) {
        while (client.connected()) {
          if (client.available()) {
            
            char c = client.read();
        
            // guarda o caracter na string 'msg'
            msg[0]=msg[1];
            msg[1]=msg[2];
            msg[2]=msg[3];
            msg[3]=msg[4];
            msg[4]= c;
            
            if (msg[4]=='#') {
              Serial.println(msg);

              LOOKS AND EXECUTE SOCKET COMMANDS
           } // Fim IF msg[4]
           else {
            //ler caractere por caractere do pedido HTTP
            if (readString.length() < 100) {
    
              //armazena os caracteres na string
              readString += c; 
              //Serial.print(c);
            }
             
            //if pedido HTTP acabou
            if (c == '\n') {
    
              ///////////////
              Serial.println(readString); //imprimir no serial para debuging 
    
              //saída de cabeçalho dos dados HTML
              if(readString.indexOf('?') >=0) { //não envia a página
                 client.println(F("HTTP/1.1 204 OK"));
                 client.println();
                 client.println();  
              }
              else {
                client.println(F("HTTP/1.1 200 OK")); //envia a página
                client.println(F("Content-Type: text/html"));
                client.println();
      
                client.println(F("<html>"));
                client.println(F("<head>"));
                client.println(F("<title>Arduino - Luzes da Casa</title>"));
                client.println(F("</head>"));
                client.println(F("<body leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\" bgcolor=\"#CCCCCC\">"));
                client.println(F("<center>"));
                client.println(F("<div style=\"background-color:#333333; color:#FFFFFF; font-size: 39px; font-weight: bold\">Luzes da Casa</div>")); 
                client.println(F("
")); 
                client.println(F("<div style=\"font-size: 21px; font-weight: bold\">Clique para Acender ou Apagar a luz.</div>"));          
                client.println(F("
"));
                client.println(F("<form method=\"get\">"));
                client.println(F("<input type=\"submit\" value=\"Quarto\" onclick=\"submit();\" name=\"luz\" style=\"height:300px; width:300px; font-size:50px\">"));
                client.println(F("<input type=\"submit\" value=\"Sala\" onclick=\"submit();\" name=\"luz\" style=\"height:300px; width:300px; font-size:50px\">"));
                client.println(F("</form>"));
                client.println(F("</center>"));
                client.println(F("</body>"));
                client.println(F("</html>"));
              }
    
              delay(1);
              //parar client
              client.stop();
    
              ///////////////////// controlar iluminação
              if(readString.indexOf("luz=Quarto") >0)//checar Quarto
              {
                if (digitalRead(4) == LOW)
                {
                  digitalWrite(4, HIGH);
                }
                else
                {
                  digitalWrite(4, LOW);
                }
                Serial.println("Web Quarto");
              }
              if(readString.indexOf("luz=Sala") >0)//checar Sala
              {
                if (digitalRead(5) == LOW)
                {
                  digitalWrite(5, HIGH);
                }
                else
                {
                  digitalWrite(5, LOW);
                }
                Serial.println("Web Sala");
              }
              //limpar string para a próxima leitura
              readString="";
            }
           } // Fim ELSE
          } // Fim client.available
        } // Fim client.connected
      }// Fim client
   }// Fim Loop

...

wow .. good reference for me to learn arduino wider :smiley:

thank you for sharing

Can anyone give this newbie a suggestion for how to incorporate login and pw verification into a webserver on arduino?
Thanks...arniep

Hi,
Here http://q.gs/4tkFt have arduino completed code to control and monitorize my reef aquarium over internet, with arduino and ethernet shield :slight_smile: :slight_smile: :stuck_out_tongue: :slight_smile:

I tried the Arduino Playground - WebServerST with the example Arduino Analog Value Displayed on Gauge on Web Page
and it did not work. The gauge only shows 0 (zero)

My code examples in the playground are not designed for a persistent connection like Ajax uses. Did you modify the code to leave the connection open for the specific file request?

I have a question about the web server, actually am interested in controlling my lights via internet. the problem is that the security cameras device is connected on port 80 and it seems that we cant use the same port for arduino ( am not sure about it but a guy from the internet company told me that)
the question is: can i use other ports like 2500 or 3000 or any other port with the web server ??
thanks 8)

I love the tutorials on the starting electronics website!

There is one thing I am trying to do, but does not work the way I want it to work.

According to the AJAX tutorials on the startingelectronics website it's possible to create a html button
and turn on a device (Relay, led, buzzer whatever).
This absolutely works.

But what about increasing or decreasing a value of a variable by 1 (only when button is pushed once)?

If you make a button with a link in it, the url will be something like http://192.168.1.177/?Button.
And as long as this url is working and the page is refreshing or kept alive, the links is working.
This is very good when you are turning on a led, relay or something like that.

But when you want to increase a value of a variable by 1 at the push of a button, the value of the variable keeps on going up as the page refreshes or is being "kept alive".

Does anyone know how to do this properly or a good tutorial for this?

Thanks in advance!

It is an Excellent tutorial!.
However, nothing has been said about the risks involved in setting up a web server
without proper Internet security.
Regards
Franco

Hi (or bette this timer: Ho, Ho, Ho :smiley: ) folks.

the tutorial site is really a good work, but the code from SurferTim (greetings and thx a lot 4 ur work) is much better!!!

i tried to make it a little bit clearer for my unprofessional eyes :astonished:
hope its ok for u Tim if i post it here.

a word to ajax: it is possible to modify Tims code also for ajax use. have tried it out and it works. but i used the original Tims-code for it. if i have make it work for the new one i will post it here for u if anyone think that it helps him (or her).

a question to SurferTim (hope u will read this):
afer the sd file is written there comes a return. in my code i saw, thet it breaks the rotine (so i think) too early. is the return necessary at this place or make i a little mistake?

my code part:

while(client.available()) client.read();

          int scanCount = sscanf(tBuf,"%7s %47s %8s",methodBuffer,requestBuffer,protocolBuffer);
          
          if(!checkRequest(&scanCount,client,tBuf,methodBuffer,requestBuffer,paramBuffer,protocolBuffer,fileName,fileType))return;
          if(!checkFile(client, fileName, fileType, tBuf,requestBuffer,methodBuffer)) return;
          else {
            openFile(client, fileName, fileType, tBuf,methodBuffer);
//fragliches return?????????????????????????????????????????????????????????????????????
            return;
          }
          serialPrintTundR(paramBuffer);

ur code part:

myFile.close();              
#ifdef ServerDEBUG
                Serial.println(F("closed"));
#endif
                client.stop();                
#ifdef ServerDEBUG
                Serial.println(F("disconnected"));
#endif
                return;//<---------- this return i mean
              }
              else {

this version of modified Tims code is the first one (finished today). there is much more to do to make it shorter and theres a lot of parameters that i give to functions that not necessary.
hope i helps the one or other to come further withhis server-projekt.
it would be nice if others help me to make it better than it is. my next step is to implement the ajax thing.

PS: please excused my broken english. am not used to comunikate in this language :slight_smile:

special thanks and greetings to SurferTim and for all of u a nice and happy chrismas.

last but not least my code from today (edit: in the atachment of the next post): (hope it would be with a slider on the side and no worm over several sites. its my first time that i post here)

posting 4 dummies :slight_smile:
overseen that i can make an atachment

here it is

WebserverST4.ino (13.3 KB)

Thanks! Happy holidays to you and yours. :slight_smile:

Why are you using a return there? My server code doesn't return there. It returns only on a fail or completion.

If you make my code shorter, you must remove something that provides error checking or fault tolerance.
Just saying...

Hi Tim, nice to meet you and thanks 4 the fast reply :slight_smile:

i dont want to make it shorter, in my 2560mega is enough memory left, thats not my ambition. i only need to seperate it in different funktions because it was too complex for me to understand what happens at what part of the code at which time.
for the future i want to modify it for ajax use and some other stuff. and so was it easyer for me to understand. am not really professional in programming and a newbie whith the arduino.
your code works great :slight_smile: , no need to make it shorter (nice trick whith the "#ifdef"), on the contrary (i want to make it longer :slight_smile: ). i only adapt it for me for the wifi shield and so i must take out the sock-things which ar not implementet in the wifi library (i think so / dont found it).

"Why are you using a return there? "
thats the question :slight_smile: i think it can be removed too.

but the return is still there in ur script and prevent the code to come to the r and t thing (what is the meaning of this part?)
i run your original code (with the wifi mods - no other changes) and the result was the same - no serial printing of r and t. but this part comes after the "if(strcmp(requestBuffer,"/MYTEST.PHP") == 0)... else" part

greetings :slight_smile:

...
pch = strtok(paramBuffer,"&");

while(pch != NULL)
{
if(strncmp(pch,"t=",2) == 0)
{
t = atoi(pch+2);
#ifdef ServerDEBUG
Serial.print("t=");
Serial.println(t,DEC);
#endif
}

if(strncmp(pch,"r=",2) == 0)
{
r = atoi(pch+2);
#ifdef ServerDEBUG
Serial.print("r=");
Serial.println(r,DEC);
#endif
}
...