Arduino Forum

Using Arduino => Interfacing w/ Software on the Computer => Topic started by: KodiakBear on Oct 28, 2012, 03:51 am

Title: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 03:51 am
Hello there,

I have a setup where Arduino Uno + Ethernet Shield connects to my localhost and receives data from data.php through GET method.
Localhost only serves the data and Arduino codes takes it into loop and receives it in delay(1);

My problem with it is that in the beginning or after some seconds of the beginning Arduino or Ethernet Shield hangs for a moment. then continues to stream the data from localhost. This issue is really unstable, it sometimes hangs couple of times and sometimes it doesn't even hang.. sometimes it hangs first then doesn't hang ever until a reset.. I left the serial monitor open all night and in the morning I saw 250.000 lines in the serial monitor although I couldn't figure out if it's hanged or not..

So anybody have experience on this kind of thing? talk to server through GET via php-mysql in realtime.

*changing delay from 1 to 100 doesn't make any difference then the mili second it self.

I am also open for any suggestions including the same setup over usb connection or wifi.

in the mean time I am so close to my deadline.
Title: Re: Uno + Ethernet Shield to PHP
Post by: PaulS on Oct 28, 2012, 03:55 am
Quote
Arduino codes takes it into loop and receives it in delay(1);

I don't think so. Nothing happens in the sitOnYourAssAndDoNothing() function. Certainly not anything like getting data from a server or client.

Some code we could look at?

What version of the IDE are you using to program the Arduino?
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 11:11 am
PaulS is right. You should post your code if you want help.

Quote
I left the serial monitor open all night and in the morning I saw 250.000 lines in the serial monitor...

That is a lot. Is this going into a MySQL database? How many entries are there?

Here is a topic that covers PHP/MySQL and the ethernet shield.
http://arduino.cc/forum/index.php/topic,124289.0.html
Reply #13 has the php and reply #15 has the Arduino code I use.
Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 01:05 pm
So this is the code I am using, it's made up from the google example.

I am using 1.0.1 and mysql entries will be flushed in every 60 seconds or something..

My actual project is controlling two different motors over two different iphones in local area network. iphones will open a web page in 192.168.1.2/whatever.php then there will be a slider there. when an iphone slides it between 0-1023 I set the speed of motors. There is no problem with controlling the motor I am only trying to make it as stable as it can be before jumping to the motor part (which is already working.) So I need somekind of realtime data stream. It doesn't have to be 1ms but it should be fast enough to see the reaction of motor when I use the slider on iphone or whatever.

(By the way I am having issue with HTTP/1.0 when it is written in the GET line, so I removed it.)




Code: [Select]

#include <SPI.h>
#include <Ethernet.h>
#include <TextFinder.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x43, 0xC4 };


char serverName[] = "192.168.1.2";


EthernetClient client;
TextFinder finder( client );
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
  }


  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
 
  if (client.connect(serverName, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /data.php");
   // client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
   
    finder.find("<");  // seek to the Results field
    long value = finder.getValue(); // get numeric value
    Serial.print(value);
    client.stop();
   
  }
  delay(1);
 
    if (!client.connected()) {
    Serial.println();
    client.stop();

  }
  if(client.connect(serverName, 80))
{
    client.println("GET /data.php");
    client.println();
}
 
}



any thoughts?
Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 01:09 pm
@SurferTim I will take a look at your example now.
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 01:18 pm
Pay close attention to how my code reads the response from the server and closes the connection. The server will close the connection when it is finished sending packets, then you close your end.

It is basically this client code in the playground.
http://www.arduino.cc/playground/Code/WebClient
Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 01:29 pm
so I changed the last two delays to 1ms to fake the data stream, it hangs on pass 25 waits a bit then continues. is this a logical stress test?


*Edit: second hang on pass 302
Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 01:35 pm
I can't be sure if this is because of Ethernet Shield or Arduino Uno? Which ones buffer full's up?

Using Arduino Mega by having more processor power and flash memory should solve this out?
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 01:39 pm

so I changed the last two delays to 1ms to fake the data stream, it hangs on pass 25 waits a bit then continues. is this a logical stress test?

*Edit: second hang on pass 302

Are you talking about my code or yours? If mine, which two delays did you change? What does the serial monitor say about that connection hang? If it is "Timeout", that takes 10 seconds before the connection will timeout and resume. That normally happens when there is a connection break, like pulling the CAT5 cable connector out of the ethernet shield or powering cycling the router.

The ethernet shield does the buffering. If the tx buffer fills up, the write function is blocking (waits for tx buffer space before returning).
Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 01:48 pm
yes I am talking about your code. there are three delays in your code first one is for ethernet shield to initialize. the rest is like this ;

Code: [Select]

if(loopCount < 30)
  {
    delay(1);
  }



Code: [Select]

    delay(1);
    connectLoop++;
    if(connectLoop > 10)


I changed these delays to 1

I don't have a router, I have a cat5 cable to my mac directly, mac is the localhost. so there is no router.

Serial monitor only says connecting... if it hangs. from that second hang on 302 it is still streaming data and it is around pass 3300 between 302 and 3300 there was no hang. which is so weird.

it hangs for 302 post and doesn't hang for 3000 posts..
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 01:54 pm
The first change is ok. The second is not. The server may not respond in 10 ms. You can change the delay to 1 ms, but you must wait at least a couple seconds before timing out. Like this is ten seconds:
Code: [Select]
   delay(1);
   connectLoop++;
   // if no packet for 10000 milliseconds
   if(connectLoop > 10000)


edit: Are you using Apache in your Mac? If so, what does the log say?

Maybe I wasn't clear about the timeout. That would only happen if the server does not either send another packet, or close the connection. Most of the time, the server response and close should be immediate. Then you would not wait nearly 10 seconds.
Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 02:29 pm
Yes I am using Mac with MAMP which is Apache..

I used the last code you sent there was no hang. then I switched back to 10ms there was no hang too..

We are also working with pc's installed WAMP, also testing there..

I believe sometimes when it starts to stream if it doesn't hang, it doesn't hang ever in that session. If I close the serial then open it back for a new session it may hang.. we have been testing this for 4 days :/

Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 02:29 pm
and I don't know how to look up to apache log.
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 02:38 pm

and I don't know how to look up to apache log.

I suggest you find out about the logs. Every time your Arduino makes that request, it should be putting an entry in the log. At your request rate, the logs can get quite large in a very short time. And Apache saves four weeks of logs.

The timeout should be left alone. When you are connected directly to the Mac, this may not be a problem. But when you put a router with a computer and an internet connection into the network, things change. But that is up to you. You can test it, and if it performs ok, use it!  :)
Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 02:44 pm
okay I will take a look at the logs now.

whole project will be working in a local area network. there won't be any router or internet connection in any time of this project scope.
Title: Re: Uno + Ethernet Shield to PHP
Post by: ahmetalpat on Oct 28, 2012, 02:50 pm
SurferTim,

Big fan of yours because of your ethernet bug solution for v1.0 IDE :)

I am working on the same project with KodiakBear.

I wrote the following code simultaneously with him. Mine is working well. The following code is working on my computer(Windows 7) without stalling. I 've tried it on 2 different XP computers and it does not stall on them as well. But we are not sure it will not stall somewhere, sometime.

Code: [Select]

#include <SPI.h>
#include <Ethernet.h>
#include <TextFinder.h>
byte mac[] = {  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
char serverName[] = "192.168.1.12";
EthernetClient client;
TextFinder finder( client );

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


 // start the Ethernet connection:
       if (Ethernet.begin(mac) == 0)
       {
         Serial.println("Failed to configure Ethernet using DHCP");
         // no point in carrying on, so do nothing forevermore:
         while(true);
       }
 // give the Ethernet shield a second to initialize:
       delay(1000);
       Serial.println("connecting...");

                   // if you get a connection, report back via serial:
                   
                           if (client.connect(serverName, 80))
                           {
                             Serial.println("connected");
                             // Make a HTTP request:
                         //    client.println("GET /data.php");
                             client.write("GET /data.php HTTP/1.0\r\n\r\n");
                           
                           }
                           else
                           {
                             // kf you didn't get a connection to the server:
                             Serial.println("connection failed");
                           }
}     //END OF SETUP

void loop()
{
 // if there are incoming bytes available
 // from the server, read them and print them:
 if (client.available())
 {
   Serial.println("Client available");
   
   //begin get user count
   finder.find("#"); //get user count
   long user_count = finder.getValue();
   Serial.print("User Count:");
   Serial.print(user_count);
   Serial.println("");
   //end get user count
   //begin get car choice
   finder.find("[");
   long car_type = finder.getValue();
   Serial.print("Car Type:");
   Serial.print(car_type);
   Serial.println("");
   // end get car choice
   // begin get first user speed
   finder.find("<");
   long speed_1 = finder.getValue();
   Serial.print("Speed 1:");
   Serial.print(speed_1); // end get first user speed
   Serial.println("");
   // end get first user speed
   // begin get second user speed
   finder.find("{");
   long speed_2 = finder.getValue();
   Serial.print("Speed 2:");
   Serial.print(speed_2);
   Serial.println("");
   // end get second user speed
   client.stop();
   //client.flush();
 
/*    int motor1_hiz = speed_1/4;
   digitalWrite(motor1_input_1, HIGH);
   digitalWrite(motor1_input_2, LOW);
   analogWrite(motor1_en,motor1_hiz);    
   
   int motor2_hiz = speed_2/4;
   digitalWrite(motor2_input_1, HIGH);
   digitalWrite(motor2_input_2, LOW);
   analogWrite(motor2_en,motor2_hiz); */
   }
   delay(100);

 
/*   if (!client.connected())
  {
   Serial.println("Client is not connected");
   client.stop();
  }*/

//This is your hack from couple months ago
/*int newFree = client.free();

if(newFree < 1000)
{
  Serial.print("Low buffer ");
  Serial.println(newFree, DEC);
}   */
 
if (client == false) // there was a bunch of code between the following and client.stop. So I wrote this. Now it is not necessary for now
{
     
   if(client.connect(serverName, 80))
  {
  //   client.println("GET /data.php");
     client.write("GET /data.php HTTP/1.0\r\n\r\n");
   //  client.write();
  //   client.println();
  }
}  
   
} // END OF CODE



Here is the serial print:
Code: [Select]

connecting...
connected
Client available
User Count:2
Car Type:1
Speed 1:706
Speed 2:470
Client available
User Count:2
Car Type:1
Speed 1:706
Speed 2:470
.
.
.


So, is it possible for you to compare two different codes and figure out what the problem might be? I think I go around the problem somewhere.

Edit: added last sentence, my bad.
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 03:05 pm
@cer: Thanks! It is now included in IDE v1.0.1.  :)

I use my code. I have already debugged it and put it in the playground.
http://www.arduino.cc/playground/Code/WebClient
It has a good connection fail timeout and response display. It should keep running no matter what happens. If it doesn't, the serial monitor should be helpful in troubleshooting. I have intentionally failed the connection during a download to test it. It recovers fine.
Title: Re: Uno + Ethernet Shield to PHP
Post by: ahmetalpat on Oct 28, 2012, 03:18 pm
Quote
@cer: Thanks! It is now included in IDE v1.0.1. 

Yeah, I saw that :) I gave you the king's crown in my mind :)

Quote
I use my code. I have already debugged it and put it in the playground.

I 'm now trying it. I'll share the results.

Thank you.
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 03:22 pm
If you are trying the same type code, then I recommend reducing the time between requests slowly. Try it at 10 seconds apart to start instead of 30 seconds. That is fast enough to test, but slow enough so you can read the serial monitor. Once that is working, then slowly reduce the time between requests.
Title: Re: Uno + Ethernet Shield to PHP
Post by: KodiakBear on Oct 28, 2012, 04:19 pm
so I have been inspecting apache logs in realtime over mac os x terminal.

it is clear that when arduino hangs on GET, Apache simply waits for GET request. There is nothing seems to be wrong in the server side.

if I change my slider in the browser when hang happens, it does send the slider value to sql according to apache logs
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 04:39 pm

so I have been inspecting apache logs in realtime over mac os x terminal.

it is clear that when arduino hangs on GET, Apache simply waits for GET request. There is nothing seems to be wrong in the server side.

if I change my slider in the browser when hang happens, it does send the slider value to sql according to apache logs

Slider?

How often are you sending requests now? Are you still waiting the one millisecond between requests?
Title: Re: Uno + Ethernet Shield to PHP
Post by: ahmetalpat on Oct 28, 2012, 05:00 pm
@SurferTim,

This is modified version of your code(http://www.arduino.cc/playground/Code/WebClient)

It works like a charm but I am still not sure if it is still stable. I mean your part of code is great, but what I did might be changed the stability.

What do you think?

Quote

/*
   Web client sketch for IDE v1.0.1 and w5100/w5200
   Posted October 2012 by SurferTim
*/

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

byte mac[] = {  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
//IPAddress ip(192,168,1,12);
//IPAddress gateway(192, 168, 1, 12);
//IPAddress subnet(255, 255, 255, 0);

IPAddress server(192,168,1,12); // Google
EthernetClient client;

int totalCount = 0;
int loopCount = 0;
char pageAdd[32];
TextFinder finder( client );
void setup() {
  Serial.begin(9600);

  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

  Ethernet.begin(mac);
  delay(2000);
  Serial.println("Ready");
}

void loop()
{
  if(loopCount < 10)
  {
    delay(10);
  }
  else
  {
    loopCount = 0;
    sprintf(pageAdd,"/data.php",totalCount);
    if(!getPage(server,pageAdd)) Serial.print("Fail ");
    else Serial.print("Pass ");
    totalCount++;
    Serial.println(totalCount,DEC);
  }    

  loopCount++;
}

byte getPage(IPAddress ipBuf,char *page)
{
  int inChar;
  char outBuf[128];

  Serial.print("connecting...");

  if(client.connect(ipBuf,80))
  {
    Serial.println("connected");

    sprintf(outBuf,"GET %s HTTP/1.0\r\n\r\n",page);
    client.write(outBuf);
  } 
  else
  {
    Serial.println("failed");
    return 0;
  }

  int connectLoop = 0;

  while(client.connected())
  {
    while(client.available())
    {
    // inChar = client.read();
   //   Serial.write(inChar);
      finder.find("<");
    long speed_1 = finder.getValue();
    Serial.print("Speed 1:");
    Serial.print(speed_1); // end get first user speed
    Serial.println("");
      
       client.flush();
    client.stop();
  /*   finder.find("<");
    long speed_1 = finder.getValue(); 
    Serial.print("Speed 1:");
    Serial.print(speed_1); // end get first user speed
    Serial.println("");*/
      connectLoop = 0;
    }
/*     if (client.available()) {
   // char c = client.read();
   // Serial.print(c);
   // Serial.println("b");
    
    finder.find("<");  // seek to the Results field
    long value = finder.getValue(); // get numeric value
    Serial.print(value);
    Serial.println("");
    client.flush();
    client.stop();
  }*/
    connectLoop++;
    if(connectLoop > 10000)
    {
      Serial.println();
      Serial.println("Timeout");
      client.stop();
    }
    delay(1);
  }

  Serial.println();

  Serial.println("disconnecting.");
  client.stop();

  return 1;
}



What does this connectLoop do by the way? It is just for testing i suppose, right?
Code: [Select]
connectLoop++;
   if(connectLoop > 100)
   {
     Serial.println();
     Serial.println("Timeout");
     client.stop();
   }

   
...and here is the serial print:
Code: [Select]
Pass 1431
connecting...connected
Speed 1:706

disconnecting.
Pass 1432
connecting...connected
Speed 1:706

disconnecting.
Pass 1433
connecting...connected
Speed 1:706

disconnecting.
Pass 1434
connecting...connected
Speed 1:706

disconnecting.
Pass 1435
connecting...connected
Speed 1:706

disconnecting.


Thank you in advance
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Oct 28, 2012, 06:03 pm
The variable connectLoop controls the timeout. If the connection breaks, like hardware fail, it prevents the "while(client.connected()" loop from becoming an endless loop. I tested that by downloading a big webpage and pulling the CAT5 connector out of the shield halfway through the download. Then a couple minutes later, after several failed connection attempts, I plugged it back in, and it went right back to working.

edit: The "while(client.connected())" loop is exited when the server sends a close message, but not a hardware fail. If the connection breaks, the close message never gets through to the client from the server, and the client code hangs in that loop.

The connectLoop counts the iterations of that loop with no packet received. With the delay(1) in the loop, it is about a millisecond through each iteration, so I used 10000 as the number of times through the loop without a packet to exit the loop with the "client.stop()" call (no packet for 10 seconds). The other comparison loops exit normally, and the last client.stop() does nothing but return if the connection is closed.
Title: Re: Uno + Ethernet Shield to PHP
Post by: ahmetalpat on Oct 28, 2012, 07:17 pm
@SurferTim

I got it. You thought of everything :) That's great, you saved my day, thank you very much!

Title: Re: Uno + Ethernet Shield to PHP
Post by: eprilya on Jul 04, 2013, 11:00 am
I have a project to control 2 servos using button on php web.
I've tried to connect the arduino to PHP then serial monitor shows this:

Code: [Select]
Starting ethernet...
192.168.0.4
Ready
connecting...connected
HTTP/1.1 200 OK
Date: Thu, 04 Jul 2013 08:47:15 GMT
Server: Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_autoindex_color PHP/5.2.8
Content-Length: 1404
Connection: close
Content-Type: text/html;charset=utf-8

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
  <title>Index of /</title>
</head>
<body>
<h1>Index of /</h1>
<pre><img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a>                    <a href="?C=M;O=A">Last modified</a>      <a href="?C=S;O=A">Size</a>  <a href="?C=D;O=A">Description</a><hr><img src="/icons/folder.gif" alt="[DIR]"> <a href="Dessy/">Dessy/</a>                  04-Jul-2013 14:26    -   
<img src="/icons/folder.gif" alt="[DIR]"> <a href="Image/">Image/</a>                  01-Jul-2013 13:35    -   
<img src="/icons/folder.gif" alt="[DIR]"> <a href="TA/">TA/</a>                     15-Jun-2013 07:31    -   
<img src="/icons/folder.gif" alt="[DIR]"> <a href="bacup/">bacup/</a>                  21-Dec-2007 09:01    -   
<img src="/icons/folder.gif" alt="[DIR]"> <a href="gagal/">gagal/</a>                  14-Jun-2013 20:58    -   
<img src="/icons/folder.gif" alt="[DIR]"> <a href="includes/">includes/</a>               01-Jul-2013 13:37    -   
<img src="/icons/folder.gif" alt="[DIR]"> <a href="jadi/">jadi/</a>                   03-Jul-2013 22:00    -   
<img src="/icons/folder.gif" alt="[DIR]"> <a href="xampp/">xampp/</a>                  21-Dec-2007 09:01    -   
<hr></pre>
<address>Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_autoindex_color PHP/5.2.8 Server at 192.168.0.2 Port 80</address>
</body></html>

disconnecting.
Pass 1


Is the information above shows that the arduino and php are connected? If yes, I don't know how to control the servos using button on php web.
Help me please
Title: Re: Uno + Ethernet Shield to PHP
Post by: PaulS on Jul 04, 2013, 02:51 pm
Quote
Is the information above shows that the arduino and php are connected?

The Arduino and the server where the php script is running connected, the php script was executed, and generated some output. The server sent that output back to you.

Quote
If yes, I don't know how to control the servos using button on php web.
Help me please


I think you are going about this all wrong. Typically, the Arduino serves up a page, containing a form with submit items. The client renders the page, and the user does something that triggers a submit item which triggers the action script. That script usually performs another GET to the server (the Arduino) containing additional information, which the Arduino parses to determine what to do.

There is nothing in the output that you showed that indicates that you made a useful GET request from the Arduino as client. All that is is an index listing from a directory, typically generated when you do not properly specify a script name, and there is an index.php script in the directory.

We'd need to see your Arduino code, and understand how you think a client is going to get useful information from the server.
Title: Re: Uno + Ethernet Shield to PHP
Post by: eprilya on Jul 05, 2013, 09:47 am

I think you are going about this all wrong. Typically, the Arduino serves up a page, containing a form with submit items. The client renders the page, and the user does something that triggers a submit item which triggers the action script. That script usually performs another GET to the server (the Arduino) containing additional information, which the Arduino parses to determine what to do.

There is nothing in the output that you showed that indicates that you made a useful GET request from the Arduino as client. All that is is an index listing from a directory, typically generated when you do not properly specify a script name, and there is an index.php script in the directory.

We'd need to see your Arduino code, and understand how you think a client is going to get useful information from the server.


Here is my php code:
Code: [Select]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Room</title>
<style type="text/css">
.alt {
font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
color: #09C;
}
.azm {
font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
color: #09C;
text-align: center;
font-weight: bold;
}
.move {
color: #FFF;
}
.alt {
color: #FFF;
}
.azm {
color: #FFF;
}
.btn {
font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
}
.txt {
color: #FFF;
}
.txt .txt {
font-weight: bold;
color: #39F;
text-align: center;
}
</style>
</head>

<body bgcolor="#000000">
<form action="form1" method="get">
<p class="txt"><span class="txt">CLICK THE BUTTON TO CONTROL TEHE TELESCOPE!</span> </p>
<table width="400" border="2" align="center">
   <tr>
     <th colspan="2" class="alt" scope="row">Altitude Control</th>
     <td colspan="2" class="azm">Azimuth Control</td>
   </tr>
   <tr>
     <th scope="row"><input type="submit" name="Move" id="Move" value="Move" /></th>
     <td><input type="submit" name="Stop" id="Stop" value="Stop" /></td>
     <td><input type="submit" name="Move2" id="Move2" value="Move" /></td>
     <td><input type="submit" name="Stop2" id="Stop2" value="Stop" /></td>
   </tr>
 </table>
</form>
</body>
</html>


When the user click move button, the servo will rotates. then when button stop was clicked, the servo will stop.
I use 4 buttons because I use 2 servos for the pan and tilt.
I don't know how to make the code for the Arduino using text finder as the previous post to connect arduino to PHP.
Title: Re: Uno + Ethernet Shield to PHP
Post by: PaulS on Jul 05, 2013, 02:53 pm
Quote
Here is my php code

That is not php code. It is nothing more than static html.

Where does that code live? If the Arduino is a client, making a GET request to a server to get that data, there is no way that the Arduino can render that code in a way that a user can interact with it.

If the Arduino is a server, serving up that page, then when the user interacts with the application that is rendering that data, the action method means that any interaction will generate a new GET request that the Arduino is supposed to deal with.

The question that you have tap danced around long enough is simple. Is the Arduino a client or is it a server? Post your code to show which it is.

If it is a client, I'll repeat my statement that you are going about this all wrong. You can't get data from a served client (a browser) from another client (the Arduino). It simply is not possible. The server doesn't even know which client it sent that page to, so there is no possible way to have the action method on that client send information to the Arduino as client.

The Arduino as client pulls data. The Arduino as server pushes data only in response to a pull request.
Title: Re: Uno + Ethernet Shield to PHP
Post by: eprilya on Jul 07, 2013, 12:30 pm

That is not php code. It is nothing more than static html.

Where does that code live? If the Arduino is a client, making a GET request to a server to get that data, there is no way that the Arduino can render that code in a way that a user can interact with it.

The Arduino as client pulls data. The Arduino as server pushes data only in response to a pull request.


I still don't understand how to make GET request. Sorry, I'm newbie =(
Before I do that, I want to ask about this.
My web is consist of some page. Then the control page is not index page.
The system is, only registered members are able to go to control page after login with username and password. How the arduino can render the code on the control page?
Title: Re: Uno + Ethernet Shield to PHP
Post by: PaulS on Jul 07, 2013, 03:35 pm
Quote
My web is consist of some page. Then the control page is not index page.
The system is, only registered members are able to go to control page after login with username and password. How the arduino can render the code on the control page?

Enough tap dancing. Your Arduino is either a client or a server. There are some things it can do as a client that it can't do as a server. There are some things it can do as a server that it can't do as a client. Post your Arduino code so we can tell which it is, since you won't directly answer the question.

I get the impression, though, that you think that a client on one machine can "see" what a browser on another machine has rendered. That is NOT possible. For any client or any browser.
Title: Re: Uno + Ethernet Shield to PHP
Post by: eprilya on Jul 08, 2013, 06:49 am

Enough tap dancing. Your Arduino is either a client or a server. There are some things it can do as a client that it can't do as a server. There are some things it can do as a server that it can't do as a client. Post your Arduino code so we can tell which it is, since you won't directly answer the question.

I get the impression, though, that you think that a client on one machine can "see" what a browser on another machine has rendered. That is NOT possible. For any client or any browser.


Here is my Arduino code to knows that the arduino and user room page are connected
Code: [Select]
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "192.168.0.2/TA/user_room.php";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,0,2);
byte gateway[] ={ 192, 168, 0, 1 };

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, gateway);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("HOST: 192.168.0.2/TA/user_room.php");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}


Then the serial monitor shows:

connecting...
connected

disconnecting.

How about this?
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Jul 08, 2013, 09:09 am
These are incorrect.
Code: [Select]
char server[] = "192.168.0.2/TA/user_room.php";
client.println("HOST: 192.168.0.2/TA/user_room.php");

Use these instead.
Code: [Select]
IPAddress server(192,168,0,2);
client.println("Host: 192.168.0.2");

Title: Re: Uno + Ethernet Shield to PHP
Post by: PaulS on Jul 08, 2013, 11:39 am
Code: [Select]
char server[] = "192.168.0.2/TA/user_room.php";    // name address for Google (using DNS)
Does that completely useless, incorrect comment really serve any purpose?

Code: [Select]
    client.println("GET /search?q=arduino HTTP/1.1");
After connecting to some bogus server (or trying to, anyway), does this GET request really make sense? It's fine if you are talking to google. It's useless when you try to talk to some other server.
Title: Re: Uno + Ethernet Shield to PHP
Post by: eprilya on Jul 09, 2013, 06:49 am

Code: [Select]
char server[] = "192.168.0.2/TA/user_room.php";    // name address for Google (using DNS)
Does that completely useless, incorrect comment really serve any purpose?

Code: [Select]
   client.println("GET /search?q=arduino HTTP/1.1");
After connecting to some bogus server (or trying to, anyway), does this GET request really make sense? It's fine if you are talking to google. It's useless when you try to talk to some other server.


I made a new code. For the example, I tried to control led using checkbox on my php. Serial monitor shows that the arduino and php are connected. But when I click the checkbox, nothing happens with the led.

Arduino code:
Code: [Select]
#if ARDUINO > 18
#include <SPI.h> // needed for Arduino versions later than 0018
#endif
#include <Ethernet.h>
#include <TextFinder.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 0, 2 }; // my php web
byte gateway[] ={ 192, 168, 0, 1 }; // router ip
byte subnet[] ={ 255, 255, 255, 0 };
//byte server[] = {209,85,229,147 }; // google
char server[] = "192.168.0.2/TA/user_room.php"; 
EthernetClient client;
TextFinder finder( client );
float value;

void setup()
{
Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, gateway);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /192.168.0.2/TA/coba_led.php?LED2=2 HTTP/1.1"); //the ip when checkbox was clicked
    //client.println("HOST: 192.168.0.2/TA/user_room.php");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
EthernetClient client;
if (client) {
TextFinder finder(client );
while (client.connected()) {
if (client.available()) {
// counters to show the number of pin change requests
int digitalRequests = 3; // output pin
if( finder.find("GET /") ) {
// find tokens starting with "pin" and stop on the first blank line
while(finder.findUntil("2", "\n\r")){ //value of led at button
char type = client.read();
int pin = finder.getValue();
int val = finder.getValue();
if( type == '2') {
Serial.print("Digital pin ");
pinMode(3, OUTPUT);
digitalWrite(pin, HIGH);
digitalRequests++;
}
else {
Serial.print("Unexpected type ");
Serial.print(type);
}
Serial.print(pin);
Serial.print("=");
Serial.println(val);
}
}
Serial.println();
// the findUntil has detected the blank line (a lf followed by cr)
// so the http request has ended and we can send a reply
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
break;
}
}
// give the web browser time to receive the data
delay(1);
client.stop();
}
}

Title: Re: Uno + Ethernet Shield to PHP
Post by: eprilya on Jul 09, 2013, 08:31 am

Code: [Select]
char server[] = "192.168.0.2/TA/user_room.php";    // name address for Google (using DNS)
Does that completely useless, incorrect comment really serve any purpose?

Code: [Select]
    client.println("GET /search?q=arduino HTTP/1.1");
After connecting to some bogus server (or trying to, anyway), does this GET request really make sense? It's fine if you are talking to google. It's useless when you try to talk to some other server.


The web to control arduino is not index.php
So, how is the  code?
Title: Re: Uno + Ethernet Shield to PHP
Post by: SurferTim on Jul 09, 2013, 12:06 pm
Code: [Select]
char server[] = "192.168.0.2/TA/user_room.php";
This returns non-existent domain using nslookup. If you use the "char server[]", it performs a dns lookup first. That domain does not resolve.

This does not do the dns resolution. It uses the ip directly.
Code: [Select]
IPAddress server(192,168,0,2);

Title: Re: Uno + Ethernet Shield to PHP
Post by: PaulS on Jul 09, 2013, 12:13 pm
Quote
Serial monitor shows that the arduino and php are connected. But when I click the checkbox, nothing happens with the led.

So, the Arduino asked the server to execute a php script and to send back the output of that script. The Arduino got some html code generated by the php script, and rendered that html code as a picture on what? You clicked the checkbox on the screen where the Arduino rendered the code?

It appears that you STILL think that the Arduino is getting some information from the client that got some information from the server. It is NOT possible for the Arduino as client to talk to another client or for another client (where you are checking the check box) to communicate with the Arduino.

Put the Arduino back in it's box, and put it away.

Go study client/server architecture, until you can see that two clients can NOT communicate directly.

Then, when you do know how client/server architecture works, get the Arduino back out IF it can do anything like you want.
Title: Re: Uno + Ethernet Shield to PHP
Post by: eprilya on Jul 14, 2013, 04:40 pm

Go study client/server architecture, until you can see that two clients can NOT communicate directly.

Then, when you do know how client/server architecture works, get the Arduino back out IF it can do anything like you want.


After I'd go to study, I think my project doesn't works well because Arduino is not possible as client. Finally, I use arduino web server to control my servo. But I've some problems, when I click button to control one servo, it doesn't stop when it's move. Here's my sketch:

Code: [Select]
#include <SPI.h>
#include <Ethernet.h>

#include <Servo.h>
Servo altitude;  // create servo object to control a servo1
Servo azimuth;  // create servo object to control a servo2

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x78, 0xEC }; //physical mac address
byte ip[] = { 192, 168, 0, 3 }; // ip in lan
byte gateway[] = { 192, 168, 0, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port


String readString;

void setup(){

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

  altitude.write(180); //set initial servo1 position if desired
  azimuth.write(180); //set initial servo2 position if desired
 
  altitude.attach(9);  //the pin for the servo1 control
  azimuth.attach(8);  //the pin for the servo2 control
  //enable serial data print
  Serial.begin(9600);
  Serial.println("server servo/pin 9,8 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

          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();

          client.print("<html><head>");
          client.print("<title>Halaman Kontrol</title>");
          client.println("</head>");
          client.print("<body bgcolor='#3399FF'>");
          client.println("<center><p><h1>Sistem Kendali Teleskop </h1></p><center><hr><br />");
         
          client.println("<form  method=get name=form>");
          client.println("<button name=b value=1 type=submit style=height:80px;width:150px><a href=\"/?altitude\"\">ALTITUDE</a></button>");
          client.println("<button name=b value=1 type=submit style=height:80px;width:150px><a href=\"/?alt_stop\"\">STOP</a></button>");
          client.println("<br />");
          client.println("<button name=b value=1 type=submit style=height:80px;width:150px><a href=\"/?azimuth\"\">AZIMUTH</a></button>");
           client.println("<button name=b value=1 type=submit style=height:80px;width:150px><a href=\"/?zm\"\">STOP</a></button>");
          client.println("</form><br />");
         
          client.println("</html></body>");
         
         delay(100);
          //stopping client
          client.stop();
         
        if(readString.indexOf("altitude") >0){
        for (int i = 0 ; i <=180; i=i+10){
            altitude.write(i);
            delay (1000);
          }
}

if(readString.indexOf("alt_stop") >0){
            altitude.write(0);
            delay (1000);
        }
       
         if(readString.indexOf("azimuth") >0){
             for (int i = 0 ; i <=180; i=i+10){
            azimuth.write(i);
            delay (1000);
          } 
         
          if(readString.indexOf("azm_stop") >0){
            azimuth.write(0);
            delay (1000);
        }
}
           readString="";
        }
      }
    }
  }
}

     


The second question is, I want to insert html code from webcam software, named "webcam xp". It is for streaming.
Can I insert this code in one table on arduino web server?

Code: [Select]
<th scope="col"><script type="text/javascript">
  var height_array = new Array();
  var width_array = new Array();
  width_array[1] = 640;
  height_array[1] = 480;
</script>
<img src="http://DESSY-PC:8080/loading.jpg" class="webcam" id="webcam1" onmousedown="PTZMouseDown1(event)" width="640" height="480" alt="Live Stream" />
<script type="text/javascript">
<!--
currentCamera1= 1;
errorimg1= 0;
document.images.webcam1.onload = DoIt1;
document.images.webcam1.onerror = ErrorImage1;
function LoadImage1()
{
        uniq1 = Math.random();
        document.images.webcam1.src = "http://DESSY-PC:8080/cam_" + currentCamera1 + ".jpg?uniq="+uniq1;
        document.images.webcam1.onload = DoIt1;
}
function PTZMouseDown1(e)
{
        var IE = document.all?true:false;
        var x,y;
        var myx,myy;
        var myifr = document.getElementById("_iframe-ptz");
        tp = getElPos1();
        myx = tp[0];
        myy = tp[1];
        if(IE){
        var scrollX = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
        var scrollY = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
        x = event.clientX - myx + scrollX;
        y = event.clientY - myy + scrollY;
        } else {
        x = e.pageX - myx;
        y = e.pageY - myy;
        }
        if ((width_array[currentCamera1] != null) && (width_array[currentCamera1] > 0)) x = Math.round((x * 400) / width_array[currentCamera1]);
        if ((height_array[currentCamera1] != null) && (height_array[currentCamera1] > 0)) y = Math.round((y * 300) / height_array[currentCamera1]);
        if (x > 400) x = 400;
        if (y > 300) y = 300;
        if (myifr != null) myifr.src = "http://DESSY-PC:8080/ptz?src=" + currentCamera1 + "&moveto_x=" + x + "&moveto_y=" + y +"";
        return true;
}
function getElPos1()
{
            el = document.images.webcam1;
            x = el.offsetLeft;
            y = el.offsetTop;
            elp = el.offsetParent;
            while(elp!=null)
              { x+=elp.offsetLeft;
                y+=elp.offsetTop;
                elp=elp.offsetParent;
              }
            return new Array(x,y);
}
function ErrorImage1()
{
        errorimg1++;
        if (errorimg1>3){
              document.images.webcam1.onload = "";
              document.images.webcam1.onerror = "";
              document.images.webcam1.src = "offline.jpg";
              }else{
                uniq1 = Math.random();
            document.images.webcam1.src = "http://DESSY-PC:8080/cam_" + currentCamera1 + ".jpg?uniq="+uniq1;
              }
}
function DoIt1()
{
        errorimg1=0;
        window.setTimeout("LoadImage1();", 40);
}
//-->
</script>
</th>
Title: Re: Uno + Ethernet Shield to PHP
Post by: PaulS on Jul 15, 2013, 01:53 pm
Quote
because Arduino is not possible as client.

Yes, it is, when you understand what a client is and what a client talks to (a server, not another client).

Code: [Select]
        //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();

Regardless of what the client asked for, give it what YOU think it needs. Wrong!!!

Quote
client.println("<button name=b value=1 type=submit style=height:80px;width:150px><a href=\"/?altitude\"\">ALTITUDE</a></button>");
          client.println("<button name=b value=1 type=submit style=height:80px;width:150px><a href=\"/?alt_stop\"\">STOP</a></button>");

Why do you have two buttons named b? Do you have two brothers named Darryl, Darryl?

Code: [Select]
          client.println("<button name=b value=1 type=submit style=height:80px;width:150px><a href=\"/?azimuth\"\">AZIMUTH</a></button>");
           client.println("<button name=b value=1 type=submit style=height:80px;width:150px><a href=\"/?zm\"\">STOP</a></button>");

Oh, wait, make that 4 buttons named b.

Code: [Select]
        if(readString.indexOf("altitude") >0){
        for (int i = 0 ; i <=180; i=i+10){
            altitude.write(i);
            delay (1000);
          }

Assuming that the client did include "altitude" in the request, this block will take 18 seconds to move the servo from 0 to 180 degrees. I fail to see how this is a relevant thing to do.

I would expect your server to have 4 buttons, named right, left, up, and down. Each request containing "right" would cause the position of one servo to be incremented by 1. Each request containing "left"would cause the position of one servo to be decremented by 1.

Each request containing "up" would cause the position of the other servo to be incremented by 1. Each request containing "down"would cause the position of that servo to be decremented by 1.

There would be no stop buttons on my page.

There might be fields where the step size could be entered. The GET request would then contain "button=right&amount=n", and you'd need to parse the statement to get the direction and the amount.

Alternatively, there might be 2 or three buttons for each direction (something like right one degree, right 5 degrees, right 20 degrees, etc.).

Quote
The second question is, I want to insert html code from webcam software, named "webcam xp". It is for streaming.
Can I insert this code in one table on arduino web server?

You can have the Arduino serve up a page that contains a placeholder for the camera image, and a source tag that says "go get the data to display here from somewhere else". You can NOT expect the Arduino to serve up the image data.