0

I have an arduino attached with a RGB-Shield. I want to query my server for the RGB values periodically. I basically got it working using the Ethernet Shield but it takes too long to get the value (~500ms}. I really want to read the values from my server really really fast in an endless loop.

Can you give me any hints on how I can improve my code?

#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,1,151); 
IPAddress ip(192, 168, 1, 177);
EthernetClient client;

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) {
    Ethernet.begin(mac, ip);
  }

  delay(1000);

  if (client.connect(server, 80)) {
    client.println("GET /rgb.php HTTP/1.1");
    client.println("Host: 192.168.1.151");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("connection failed");
  }
}


void loop()
{
  if (client.available()) {
    char c = client.read();

    ... read from Server    

  }


  if (!client.connected()) {
    client.stop();
    if (client.connect(server, 80)) {
      client.println("GET /rgb.php HTTP/1.1");
      client.println("Host: 192.168.1.151");
      client.println("Connection: close");
      client.println();
    }   
  }
}
2
  • you may use mqtt protocol, it support push notifications instead of polling and it's way lighter Nov 14 '15 at 7:55
  • Yeah I thought about that, but I could not imagine that push is faster than polling. Is it?
    – matthias
    Nov 14 '15 at 7:57
1

You could try with a direct TCP connection (in this way you skip the HTTP layer) but you need to prepare also a small TCP server (in any language comfortable to you) that accepts the client connection, sends the data, waits the ACK and close the connection.

0

I would start with this section:

if (client.connect(server, 80)) {
  client.println("GET /rgb.php HTTP/1.1");
  client.println("Host: 192.168.1.151");
  client.println("Connection: close");
  client.println();
}

How many messages does the Arduino Ethernet library send for this block? Actually due to the implementation of the Arduino Print and EthernetClient class it sends 7 messages (no joke!). It does not collect this into a single message/frame.

The first optimization is to print a single string and send that as one frame.

  #define CR "\r\n"

  client.print("GET /rgb.php HTTP/1.1" CR
               "Host: 192.168.1.151" CR
               "Connection: close" CR
               CR);

Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy