emonlib with ajax web server is very slow

Hi again guys,

Now I'm facing a new problem that I cannot manage, and looking forward for your help.

On Arduino Mega with W5100 I have setup a web server on SD card. So, I want to switch a led on/off from Index.html stored on card (with ajax), and everything is fine, but when I want to include the reading of 3 phases AC current everything is going very slow, and I cant figure out where is the problem? Please help!

My code without emonlib:

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   60

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

void setup()
{
    // disable Ethernet chip
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);
    
    Serial.begin(9600);       // for debugging
    
    // initialize SD card
    Serial.println("Initializing SD card...");
    if (!SD.begin(4)) {
        Serial.println("ERROR - SD card initialization failed!");
        return;    // init failed
    }
    Serial.println("SUCCESS - SD card initialized.");
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERROR - Can't find index.htm file!");
        return;  // can't find index file
    }
    Serial.println("SUCCESS - Found index.htm file.");
    // LEDs
    pinMode(8, OUTPUT);
    
    Ethernet.begin(mac, ip);  // initialize Ethernet device
    server.begin();           // start to listen for clients
}

void loop()
{
    EthernetClient client = server.available();  // try to get client

    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // limit the size of the stored received HTTP request
                // buffer first part of HTTP request in HTTP_req array (string)
                // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
                if (req_index < (REQ_BUF_SZ - 1)) {
                    HTTP_req[req_index] = c;          // save HTTP request character
                    req_index++;
                }
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    // remainder of header follows below, depending on if
                    // web page or XML page is requested
                    // Ajax request - send XML file
                    if (StrContains(HTTP_req, "ajax_inputs")) {
                        // send rest of HTTP header
                        client.println("Content-Type: text/xml");
                        client.println("Connection: keep-alive");
                        client.println();
                        SetLEDs();
                    }
                    else {  // web page request
                        // send rest of HTTP header
                        client.println("Content-Type: text/html");
                        client.println("Connection: keep-alive");
                        client.println();
                        // send web page
                        webFile = SD.open("index.htm");        // open web page file
                        if (webFile) {
                            while(webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }
                            webFile.close();
                        }
                    }
                    // display received HTTP request on serial port
                    Serial.print(HTTP_req);
                    // reset buffer index and all buffer elements to 0
                    req_index = 0;
                    StrClear(HTTP_req, REQ_BUF_SZ);
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                } 
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
}
void SetLEDs(void)
{
    // RelayImpulse1 (pin 8)
    if (StrContains(HTTP_req, "RelayImpulse1=1")) {
        digitalWrite(8, HIGH);
        delay(100);
        digitalWrite(8, LOW); 
    }
    else if (StrContains(HTTP_req, "RelayImpulse1=0")) {
        digitalWrite(8, HIGH);
        delay(100);
        digitalWrite(8, LOW); 
    }
}
void StrClear(char *str, char length)
{
    for (int i = 0; i < length; i++) {
        str[i] = 0;
    }
}
char StrContains(const char *str, const char *sfind)
{
    char found = 0;
    char index = 0;
    char len;

    len = strlen(str);
    
    if (strlen(sfind) > len) {
        return 0;
    }
    while (index < len) {
        if (str[index] == sfind[found]) {
            found++;
            if (strlen(sfind) == found) {
                return 1;
            }
        }
        else {
            found = 0;
        }
        index++;
    }

    return 0;
}

This will work fast enough, but when I put the following code I loose some inputs sent from webpage, my arduino will block and everything is so slow... (30 sec or more).

#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon1;                   // Create an instance
EnergyMonitor emon2;                   // Create an instance
EnergyMonitor emon3;                   // Create an instance


void setup()
{
emon1.current(3,17.0);             // Current: input pin, calibration.
    emon2.current(4,17.0);             // Current: input pin, calibration.
    emon3.current(5,17.0);             // Current: input pin, calibration.
}

void XML_response(EthernetClient cl)
{

double Irms1 = emon1.calcIrms(2000);  // Calculate Irms only
double Irms2 = emon2.calcIrms(2000);  // Calculate Irms only
double Irms3 = emon3.calcIrms(2000);  // Calculate Irms only


// read analog pin A3
cl.print("<analog>");
  cl.print(" ");
  cl.print(Irms1*230.0/1000);         // Apparent power
  cl.println("</analog>");
  cl.print("<analog>");
  cl.print(" ");
  cl.println(Irms1);          // Irms
cl.println("</analog>");

// read analog pin A4
cl.print("<analog>");
  cl.print(" ");
  cl.print(Irms2*230.0/1000);         // Apparent power
  cl.println("</analog>");
  cl.print("<analog>");
  cl.print(" ");
  cl.println(Irms2);          // Irms
cl.println("</analog>");

// read analog pin A5
cl.print("<analog>");
  cl.print(" ");
  cl.print(Irms3*230.0/1000);         // Apparent power
  cl.println("</analog>");
  cl.print("<analog>");
  cl.print(" ");
  cl.println(Irms3);          // Irms
cl.println("</analog>");


// read current sum
cl.print("<analog>");
  cl.print(" ");
  cl.print((Irms1+Irms2+Irms3)*230.0/1000);         // Apparent power
  cl.println("</analog>");
  cl.print("<analog>");
  cl.print(" ");
  cl.println(Irms1 + Irms2 + Irms3);          // Irms
cl.println("</analog>");

}

Please ,help me with some idea or code example, because I'm stuck (end very beginner).
Thank you!

What does the index.html file contain? Why do you NEED to use ajax?

Paul, I use ajax for the webpage to be smooth and sincerly that is the code that I found on net. And I want to put more sensors and not to load all page that contains photos too.

The webpage I can post it when I go home.

But, is there another way to change this:

cl.print(Irms3*230.0/1000);

or this:

cl.print((Irms1+Irms2+Irms3)*230.0/1000);

...or my problem is not from here?

Thank you!

This is slow. Sends one byte per packet.

                            while(webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }

Use something like this instead. It sends 64 bytes per packet. A 4x improvement in speed.

                  while(myFile.available()) {
                    clientCount = myFile.read(tBuf,64);
                    client.write((byte*)tBuf,clientCount);
                  }

Use something like this instead. It sends 64 bytes per packet. A 4x improvement in speed.

64 bytes per packet vs. 1 byte per packet is only a 400% improvement in speed?