Ethernet POST to server

Hello all, I'm stuck on a part of my program again and need some help from some one please. I know there are excellent programmers here how can help.

I have a web site with a PHP script running. On the script is a couple of buttons then when pressed send a GET function to my arduino to turn on an LED.

This all works very well and I can turn on and off an LED from anywhere that I have internet access.

What I am struggling to do it send back to my server that the arduino has turned on the LED so the web page will display LED ON.

i have tried putting in a GET script to return back to my web page. This works but the URL is changed to www.mywebpage.com/file.php?led=1

the ?led=1 stops the rest of my web page displaying.

i think this could be overcome by sending back the information using POST. But I don't know how to do this.

My arduino code is below

#include <SPI.h>
#include <Ethernet.h>
int led = 2;
int led1 = 9;
int led2 = 8;
 
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
byte ip[] = { ***, ***, *, ** };                      // ip in lan (that's what you need to use in your browser. ("***.***.*.***")
byte gateway[] = { ***, **, **, * };                   // internet access via router

EthernetServer server(****);                             //server port     
String readString;

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  pinMode(led, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip );
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}


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
     
           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("<meta name='apple-mobile-web-app-capable' content='yes' />");
           client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
           client.println("POST /TempGauges.php HTTP/1.1");
           client.println("Host: MyWebPage.com");
           client.println("led=1"); 
           
           client.println("</HEAD>");
           client.println("<BODY>");
           client.println("<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=http://www.MyWebPage.com/TempGauges.php\">");
           client.println("</BODY>");
           client.println("</HTML>");
     
           delay(1);
           //stopping client
           client.stop();
           //controls the Arduino if you press the buttons
           if (readString.indexOf("?button1on") >0){
               digitalWrite(led, HIGH);
               Serial.println ("LED 0n");
           }
           if (readString.indexOf("?button1off") >0){
               digitalWrite(led, LOW);
           }
           if (readString.indexOf("?button2on") >0){
               digitalWrite(led1, HIGH);
           }
           if (readString.indexOf("?button2off") >0){
              digitalWrite(led1, LOW);
                } 
           if (readString.indexOf("?button3on") >0){
             digitalWrite(led2, HIGH);
           }
           if (readString.indexOf("?button3off") >0){
             digitalWrite(led2, LOW);
         }
      
           
            //clearing string for next read
            readString="";  
           
         }
       }
    }
}
}

Can anyone help.

thank you:)

On the script is a couple of buttons then when pressed send a GET function to my arduino to turn on an LED.

No. The script sends a GET REQUEST. The GET request is handled by a server which CAN return a reply (and usually does). As yours does. Handling the GET request BEFORE sending the response might prove useful.

i have tried putting in a GET script to return back to my web page. This works but the URL is changed to www.mywebpage.com/file.php?led=1

Your setup seems somewhat complicated. What does the browser client communicate with, the php server or the arduino server?

It's hard to be sure based on the very incomplete code you provided, but the page your Arduino is sending to the browser is doing a re-direct to www.MyWebPage.com/TempGauges.php, and THAT is what is generating the GET request.

Odd too that the code you posted never actually looks at the request from the server, so has no way of knowing what it's asking for, except for the few key/value pairs you look for. It really should be parsing the entire request, making sure it is a valid GET or POST, and using the URI to determine what to do. That is an exceedingly fragile and limited implementation of a web server.

Regards,
Ray L.

Hello All

first thank you for the replies, I will try and give as much information in the reply back. To start below is a copy of the PHP script on my web site.

<html>

<head>

<title> temperature control </title>



<meta http-equiv="refresh" content="30">



<script src="raphael.2.1.0.min.js"></script>

<script src="justgage.1.0.1.min.js"></script>


<?php
include 'Mysql Temp Query.php';
?>


</head>

<body>



<table align = center >


<tr align = center>


<td colspan="2" bgcolor="#0ffh00" ><font size="30"> Temperature Control </font> </td>
</tr>


<tr>

<td align = right width="50%" bgcolor="#000000">

<div id="gauge" style="width:210px; height:130px"></div>




<script>

  var g1 = new JustGage({

  id: 'gauge',

  value:
  <?php echo "$outSideTemp"; ?>

  ,

  min: 0,
 
  max: 100,
 
  relativeGaugeSize: true,
 
  donut: true,
 
  titleFontColor: '0fff00',
 
  valueFontColor: '0fff00',
 
  title: 'Out Side Temp'
});

</script>



<div id="waterTemp" style="width:210px; height:130px"></div>




<script>
 
 
  var g1 = new JustGage({
 
  id: 'waterTemp',
 
  value: 
 
  <?php echo "$upperTemp"; ?>
 
  ,
 
  min: 0,
 
  max: 100,
 
  relativeGaugeSize: true,
 
  donut: true,
 
  titleFontColor: 'cc00cc',
 
  valueFontColor: 'cc00cc',
 
  title: 'Water Temp'
});

</script>



<div id="rayburn" style="width:210px; height:130px"></div>




<script>
 
 
  var g1 = new JustGage({
  id: 'rayburn',

  value: 
 
  <?php echo "$rayburn"; ?>
 
  ,
 
  min: 0,
 
  max: 100,
 
  relativeGaugeSize: true,
 
  donut: true,
 
  titleFontColor: '66ffff',
 
  valueFontColor: '66ffff',
 
  title: 'Rayburn'
});

</script>



<div id="panel" style="width:210px; height:130px"></div>



<script>
 
 
  var g1 = new JustGage({
 
  id: 'panel',
 
  value: 
 
  <?php echo "$panel"; ?>
 ,
 
  min: 0,
 
  max: 100,
 
  relativeGaugeSize: true,
 
  donut: true,
 
  titleFontColor: '99ff00',
 
  valueFontColor: '99ff00',
 
  title: 'Solar Panel'
});

</script>


</td>
<td align = center width="50%" bgcolor="#000000">



<form><input type="button" value="Yellow OFF" onClick="window.location.href='http://MyArduino ip address/?button1off'"></form>

<form><input type="button" value="Yellow ON" onClick="window.location.href='http://MyArduino ip address/?button1on'"></form>
<form><input type="button" value="Blue OFF" onClick="window.location.href='http://MyArduino ip address/?button2off'"></form>

<form><input type="button" value="Blue ON" onClick="window.location.href='http://MyArduino ip address/?button2on'"></form>

<form><input type="button" value="White OFF" onClick="window.location.href='http://MyArduino ip address/?button3off'"></form>

<form><input type="button" value="White ON" onClick="window.location.href='http://MyArduino ip address/?button3on'"></form>




</td>
</tr>



<?php

$led1 = $_POST['led'];

print ("LED = ");
print $led1;


?>

 
</body>
 
</html>

The PHP script sends a GET REQUEST when clicking one of the buttons to turn on the LED. This is done by the following line

<form><input type="button" value="Yellow OFF" onClick="window.location.href='http://MyArduino ip address/?button1off'"></form>

The Arduino receives this information and turns on the relevant LED depending on if the return was button1on or button1off.

The Arduino was displaying a HTML page which my web site was sending the GET request to. This page is not displaying anything but has a redirect back to my Web page on my LCN server. This part of the program works well although it may not be good way to do this. (I'm still learning and this is the first time I have got this to work).

So when a button is clicked on my web page the arduino turns the LED on.

What I then wanted was to have the arduino reply to my web site to say the LED is turned on.

I put in my arduino code the following with in the client part.

           client.println("POST /TempGauges.php HTTP/1.1");
           client.println("Host: MyWebPage.com");
           client.println("led=1");

This was in hope to POST back that LED1 was on and be received by the PHP page script.

<?php

$led1 = $_POST['led'];

print ("LED = ");
print $led1;


?>

But this does not work.

I have got it to return a GET request but it changes my web address from

www.stevsolarhome.com/TempGauges.php

to

www.stevesolarhome.com/TempGauges.php?led=1

this added part to the end of the URL stopped the graphical dials displaying on my page.

I understand there is some code in the Arduino sketch that does not need to be there I'm working on stream lining this better.

I will also be happy with any advice on making this better.

MY main goal is to control something on the Arduino from my web site, the displayed web site is on my LCN server and not the Arduino. I then want the Arduino to tell the web page what has been activated.

Any help is much appreciated.

Thank you

This is the original arduino code before i put the POST request in

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
     
           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("<meta name='apple-mobile-web-app-capable' content='yes' />");
           client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
           
           client.println("</HEAD>");
           client.println("<BODY>");
           client.println("<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=http://www.MyWebPage.com/TempGauges.php\">");
           client.println("</BODY>");
           client.println("</HTML>");
     
           delay(1);
           //stopping client
           client.stop();

           //controls the Arduino if you press the buttons
           if (readString.indexOf("?button1on") >0){
               digitalWrite(led, HIGH);
               Serial.println ("LED 0n");
           }
           if (readString.indexOf("?button1off") >0){
               digitalWrite(led, LOW);
           }
           if (readString.indexOf("?button2on") >0){
               digitalWrite(led1, HIGH);
           }
           if (readString.indexOf("?button2off") >0){
              digitalWrite(led1, LOW);
                } 
           if (readString.indexOf("?button3on") >0){
             digitalWrite(led2, HIGH);
           }
           if (readString.indexOf("?button3off") >0){
             digitalWrite(led2, LOW);
         }
      
           
            //clearing string for next read
            readString="";  
           
         }
       }
    }
}
}

To start below is a copy of the PHP script on my web site.

Why are

you wasting our

time with all the useless

white space?

The Arduino was displaying a HTML page

Highly unlikely. It might be serving up a web page, but the likelihood of is DISPLAYING a web page approaches ZERO.

         //if HTTP request has ended
         if (c == '\n') {          
           Serial.println(readString); //print to serial monitor for debuging
     
           client.println("HTTP/1.1 200 OK"); //send new page

If there was a GET request, return a response.

           //stopping client
           client.stop();

           //controls the Arduino if you press the buttons
           if (readString.indexOf("?button1on") >0){
               digitalWrite(led, HIGH);
               Serial.println ("LED 0n");
           }
           if (readString.indexOf("?button1off") >0){
               digitalWrite(led, LOW);
           }

Then, tell the client to f**k off. Finally, deal with what the client asked you to do.

NO! NO! NO!

Deal with what the client asked you to do and THEN generate the response, which includes whether or not the LED is on.

Ok so I can carry out the turning led on or off then send the response of the LED state.

Problem still with sending the response GET changes the URL and stops my java on the web page from running.

If I send this back as POST would this not change the URL and if not how do I send back as POST. (not been able to use POST from Arduino before)

Or im thinking of sending the pin status to MySql data base and web page get status from this.

Thanks paul for the reply. will have a play with what you said.

i assume when you mean white space the blank lines in the code. If so agree I do this when learning so i can read it easily. :smiley:

The "?led=1" is the data associated with the GET response to a button push on the client. It is NOT part of the URL. I think you need to learn more about how GET and POST actually work....

Regards,
Ray L.

The GET response is attached the the URL and when the arduino redirects back to my page this is on the URL. I understand the GET is visual on the URL where as POST is not.

I have been using GET for some time with no problems.

I have just incorporated the data base to update the web page from the Arduino, all is working on the server side just need to see if the arduino sketch works. code below.

Will hopefully will try this tonight and if ok will sort out the the part paul has pointed out.

#include <SPI.h>
#include <Ethernet.h>
int led = 6;
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
byte ip[] = {***, ***, *, **};  //arduino ip address
EthernetServer server(***9);	//port forwarded on router looking at arduino ip
String readString;

void setup(){
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print ("Serveris at ");
  Serial.println (Ethernet.localIP());
}
 
void loop (){
  
  EthernetClient client = server.available();
  if (client){
    while (client.connected()){
      if (client.available()){
        char c = client.read();
        if (readString.length() < 100){
          readString += c;
          Serial.println (c);
        }
      if (c == '\n'){
        Serial.println(readString);
        client.println ("HTTP/1.1 200 OK");              // reply back from GET REQUEST
        client.println ("content-Type: text/html");
        client.println ();
        client.println ("<HTML>");
        client.println ("<head>");
        client.println ("</head>");
        client.println ("<body>");
        client.println ("<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=http://www.stevesolarhome.com/TempGauges.php\">");   // return back to WEB page
        client.println ("</body>");
        client.println ("<html>");
        delay (1);
        client.stop();
        // turn LED on or OFF dependent on GET REQUEST
        if (readString.indexOf("?button1on") >0){
          digitalWrite (led, HIGH);
          Serial.println("LED ON");
          updateDb ();              //update MySQL data base with pin status
        }
        
        if (readString.indexOf("?buttonoff") >0){
          digitalWrite(led, LOW);
          Serial.println("LED OFF");
          updateDb ();
        }
        readString="";
      }
      }
    }
  }
}

void updateDb (){

    Serial.println ("send data");
    EthernetClient client = server.available();
    if (client){
    while (client.connected()){
    Serial.println("connected to send data");    
    client.print("GET /db_update.php?pin6=");//send panel = to server
    client.print(led);
    client.println(" HTTP/1.0");// add to end of GET send with println
    client.println("Host: www.Mywedaddress.com");// my web host address
    client.println(); //end of get request
    Serial.println ("end send data");
  } 
    }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }
  while(client.connected() && !client.available()) delay(1); //waits for data
   int noCharCount = 0;
  while(client.connected())
  {
    while(client.available())
    {
      char c = client.read();
      Serial.write(c);
      noCharCount = 0;
    }
    delay(10);
    noCharCount++;
    // change this value to suit you. this is 10 seconds    
    if(noCharCount > 1000)
    {
      Serial.println();
      Serial.println("Timeout");
      client.stop();
    }
      }
}

Problem still with sending the response GET changes the URL and stops my java on the web page from running.

A high level issue you need to work on is the fact that if there is more than one person able to use the control page on their browser, then you will not know the LED status has changed until something checks the current status of the arduino. For accurate current status of the LED, a current request needs to be made to the arduino to check the LED status. Status request are often made via meta refresh or javascript code contained in the main web page. Simple status pages can be embedded in the main web page to provide the info. The below tutorial has some info.

Thanks ZoomKat will have a read over this.

If I run this so the WEB page sends a request to turn the LED on, then the Arduino sends an update to MySql of the pin status HIGH or LOW. The web page will then update from the database.

would this not work the same.

This will also then allow the Arduino program to make a pin high due to certain conditions and change the WEB sites condition.

The web page will then update from the database.

I would just get an update directly from the arduino and skip the database part.

Well the Arduino code did not work. DB not updated. thought it was a long shot.

I have got two arduino sketches. One will turn an LED on when web button operated, and a separate sketch that can update mysql with a digital or analog reading from the arduino. but i can't get both to work together.

My project is to have an alarm that can be armed/disarmed by a web site and also armed/disarmed by switch to arduino. in both cases the site will show the state of the alarm. this is why i thought the db would be the best way forward.

I will have a read over the Ajax function as this looks like a way forward. or I could run two arduinos. one for web site inputs one to update the database with alarm conditions.

any thought on what way i should go and start reading up on

zoomkat thank for the reply. probably will have to go this way.

Zoomcat, ive had a quick scan over the link you sent thanks, this is something i needed. I will spend a couple days going over these tutorials.

do you know any good books for Arduino and web control

Simple code showing getting updated data from an arduino web server.

// zoomkat's meta refresh data frame test page 5/25/13
// use http://192.168.1.102:84 in your brouser for main page
// http://192.168.1.102:84/data static data page
// http://192.168.1.102:84/datastart meta refresh data page
// for use with W5100 based ethernet shields
// set the refresh rate to 0 for fastest update
// use STOP for single data updates

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

const int analogInPin0 = A0;
const int analogInPin1 = A1;
const int analogInPin2 = A2;
const int analogInPin3 = A3;
const int analogInPin4 = A4;
const int analogInPin5 = A5;

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 102 }; // arduino 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
unsigned long int x=0; //set refresh counter to 0
String readString; 

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

void setup(){
  Serial.begin(9600);
    // disable SD SPI if memory card in the uSD slot
  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

  Ethernet.begin(mac, ip, gateway, gateway, subnet);
  server.begin();
  Serial.println("meta refresh data frame test 5/25/13"); // so I can keep track of what is loaded
}

void loop(){
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
         if (readString.length() < 100) {
          readString += c; 
         } 
        //check if HTTP request has ended
        if (c == '\n') {

          //check get atring received
          Serial.println(readString);

          //output HTML data header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          //generate data page
          if(readString.indexOf("data") >0) {  //checks for "data" page
            x=x+1; //page upload counter
            client.print("<HTML><HEAD>");
            //meta-refresh page every 1 seconds if "datastart" page
            if(readString.indexOf("datastart") >0) client.print("<meta http-equiv='refresh' content='1'>"); 
            //meta-refresh 0 for fast data
            if(readString.indexOf("datafast") >0) client.print("<meta http-equiv='refresh' content='0'>"); 
            client.print("<title>Zoomkat's meta-refresh test</title></head><BODY>
");
            client.print("page refresh number: ");
            client.print(x); //current refresh count
            client.print("

");
            
              //output the value of each analog input pin
            client.print("analog input0 is: ");
            client.print(analogRead(analogInPin0));
            
            client.print("
analog input1 is: ");
            client.print(analogRead(analogInPin1));
                        
            client.print("
analog input2 is: ");
            client.print(analogRead(analogInPin2));
            
            client.print("
analog input3 is: ");
            client.print(analogRead(analogInPin3));
                                    
            client.print("
analog input4 is: ");
            client.print(analogRead(analogInPin4));
            
            client.print("
analog input5 is: ");
            client.print(analogRead(analogInPin5));
            client.println("
</BODY></HTML>");
           }
          //generate main page with iframe
          else
          {
            client.print("<HTML><HEAD><TITLE>Zoomkat's frame refresh test</TITLE></HEAD>");
            client.print("Zoomkat's Arduino frame meta refresh test 5/25/13");
            client.print("

Arduino analog input data frame:
");
            client.print("&nbsp;&nbsp;<a href='http://192.168.1.102:84/datastart' target='DataBox' title=''yy''>META-REFRESH</a>");
            client.print("&nbsp;&nbsp;&nbsp;&nbsp;<a href='http://192.168.1.102:84/data' target='DataBox' title=''xx''>SINGLE-STOP</a>");
            client.print("&nbsp;&nbsp;&nbsp;&nbsp;<a href='http://192.168.1.102:84/datafast' target='DataBox' title=''zz''>FAST-DATA</a>
");
            client.print("<iframe src='http://192.168.1.102:84/data' width='350' height='250' name='DataBox'>");
            client.print("</iframe>
</HTML>");
          }
          delay(1);
          //stopping client
          client.stop();
          //clearing string for next read
          readString="";
        }
      }
    }
  }
}

Thanks zoomkat, this sketch is helpfull and one for me to keep maybe use on another idea i have. The problem I have at present is the web page im hosting is not on the Arduino its on a Host site.

I know how to upload digital and analogue signals to the web page and how to read digital and analogue signals from the web site to the arduino using GET request.

What I can't do is make a variable state HIGH on the arduino from the web site. then read this back to the web site from the Arduino so that the web site shows the state of the variable.

So i will be able to turn the variable (say LED pin6) high and low from the web site and display this state on the web site, I could also turn this variable high and low from a switch input to the arduino which also changes the state of the web page.

I might create this all on the Arduino as a web page from the SD card as this may be easier, but need to see if i can run the current js dials i have on my web page.

my current page is at http://stevesolarhome.com/TempGauges.php

the HOT WATER on/off is what im trying to do. turn on/off by web page which will change the color from red/green but still have control from home and update the site.

Thanks for all your help. will carry on learning the link you sent and see if this helps