Help debugging client connected ethernet shield [SOLVED]

Hello, need your help again debugging an issue that is driving me crazy...
I can't get the code to pass the IF (client) statement when there is a client connected to the ip adress of ethernet shield. i've done a lot of debugging but i can't see why... could you please look at my code and tell me what is wrong?

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

//DECLARAÇÃO DOS PINOS
const byte ledInfo = 2;
const byte ledRececao = 3;
const byte pinoRececao = 8;
const byte BUFSIZ = 128;

//DECLARAÇÃO DAS VARIÁVEIS GLOBAIS
char mensagem[5];
unsigned int dadosAgua = 0;
float dadosBat = 0; //confirmar se é melhor float ou int
float percentagem = 0;
unsigned long litros = 0;
unsigned int nrLeitura = 1;
boolean Log = false;

//CONFIGURAÇÃO DO ETHERNET SHIELD
byte mac[] = {0x80, 0xA2, 0xDA, 0x00, 0xEA, 0x8C};
IPAddress ip = (196, 168, 0, 3);
char ficheiroIndex[] = "index.htm";
char ficheiroLog[] = "&logg.txt";
char ficheiroTanque[] = "tanque.jpg";
char ficheiroBorder[] = "border.jpg";
char ficheiroRodape[] = "rodape.jpg";
char ficheiroIframe[] = "iframe.htm";
char ficheiro2Iframe[] = "2iframe.htm";
char* ficheiroLer = '\0';
EthernetServer server(80);
EthernetClient client;

//PROGRAMAÇÃO DO CARTÃO SD
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;
SdFile LOGfile;

//ARMAZENA SEQUÊNCIAS DE ERRO NA MEMÓRIA FLASH PARA ECONOMIZAR RAM
#define error(s) error_P(PSTR(s))
void error_P(const char* str) {
  PgmPrint("Erro: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("Erro cartao SD: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  digitalWrite(ledInfo, HIGH);
  while(1);
}

void setup() {

  Serial.begin(9600);
  delay(100);

  pinMode(ledInfo, OUTPUT);
  pinMode(ledRececao, OUTPUT);
  pinMode(10, OUTPUT);

  //LIGA E DESLIGA OS 2 LEDS PARA INDICAR QUE ESTÃO OPERACIONAIS
  digitalWrite(ledInfo, HIGH);
  digitalWrite(ledRececao, HIGH);
  digitalWrite(10, HIGH);
  delay(1000);
  digitalWrite(ledInfo, LOW);
  digitalWrite(ledRececao, LOW);

  PgmPrint("Memoria RAM Livre: ");
  Serial.println(FreeRam());

  //INICIALIZA O CARTÃO SD EM "FULL SPEED", MÁXIMO DESEMPENHO. (PARA EVITAR ERROS COM LIGAÇÃO À BREADBOARD DEVE ESTAR EM "HALF SPEED")
  if (!card.init(SPI_FULL_SPEED, 4)) error("Falha ao inicializar o Cartão SD!");

  //INICIALIZA O VOLUME FAT
  if (!volume.init(&card)) error("Falha ao inicializar Volume do Cartão SD!");
  PgmPrint("O volume e FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();

  //LISTA NA SÉRIE OS FICHEIROS QUE ESTÃO NA RAIZ DO CARTÃO SD, COM DATA E TAMANHO
  if (!root.openRoot(&volume)) error("Falha ao abrir raiz do cartao!");
  PgmPrintln("Ficheiros na raiz do cartao:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();

  //LISTA OS FICHEIROS DE TODOS OS DIRECTÓRIOS DO CARTÃO SD
  PgmPrintln("Ficheiros encontrados em todos os directorios do cartao:");
  root.ls(LS_R);
  Serial.println();
  PgmPrintln("Concluida a inicializacao do Cartao SD");

  //ESCREVE O CABEÇALHO DO FICHEIRO DE DATALOGGER
  Log = file.open(&root, ficheiroLog, O_WRITE | O_APPEND);
  if (Log){
    file.println("Leitura  ,  Nivel Tanque  ,  Quantidade Agua");
    file.close();
    Serial.println(F("Escrita do header no ficheiro LOG concluida!"));
  }
  else{ 
    Serial.println(F("ERRO! Nao foi possivel abrir o ficheiro LOG."));

    //SE NÃO CONSEGUIR ABRIR O FICHEIRO LOG, LED FICA A PISCAR PARA INDICAR AVARIA    
    while(true) {
      digitalWrite(ledInfo, HIGH);
      delay(1000);
      digitalWrite(ledInfo, LOW);
      delay(1000);
    }  
  }

  //INICIA O SERVIDOR
  Ethernet.begin(mac, ip);
  server.begin();
  delay(100);

  //CONFIGURA E INICIA O RECEPTOR
  vw_set_rx_pin(pinoRececao);
  vw_setup(2000);
  vw_rx_start();

  //LED PISCA 3 VEZES A INDICAR TODA A CONFIGURAÇÂO CONCLUÍDA COM SUCESSO
  for (int i = 0; i<3; i++) {
    digitalWrite(ledInfo, HIGH);
    delay(250);
    digitalWrite(ledInfo, LOW);
    delay(250);
  }
  Serial.println(F("Configuracao Concluida"));
}

void loop() {

  rececaoRF();
  clienteLigado();
}

//RECEPÇÃO DOS DADOS POR RF 433MHz
void rececaoRF() {

  byte buf[VW_MAX_MESSAGE_LEN];
  byte buflen = VW_MAX_MESSAGE_LEN;

  if (vw_get_message(buf, &buflen)) {
    digitalWrite(ledRececao, HIGH);
    for (int j = 0; j<buflen; j++) {
      mensagem[j] = buf[j];
    }
    if (mensagem[0] == 'R') {
      dadosAgua = atoi(&mensagem[1]);
      percentAgua();
    } 
    else if (mensagem[0] == 'B') {
      dadosBat = atoi(&mensagem[1]);
      litrosAgua();
    }
    Serial.print(F("Mensagem Recebida: "));
    Serial.println(mensagem);
    memset(&buf, 0, sizeof(buf));
    memset(&mensagem, 0, sizeof(mensagem));
    gravarDados();
  }
  Serial.println(F("RececaoRF Concluida"));
}

void percentAgua() {
  percentagem = ((465-dadosAgua)*100)/465;
  Serial.print(F("Percentagem: "));
  Serial.println(percentagem);
}

void litrosAgua() {
  litros = ((465-dadosAgua)*700000)/465;
  Serial.print(F("Litros: "));
  Serial.println(litros);
}

void gravarDados() {
  Log = file.open(&root, ficheiroLog, O_WRITE | O_APPEND);
  if (Log){
    file.print(nrLeitura);
    file.print("  ,  ");
    file.print(percentagem, 1);
    file.print("  ,  ");
    file.println(litros);
    file.close();
    Serial.println(F("Valores gravados com sucesso!"));
    nrLeitura++;
    Log = false;
  } 
  else {
    Serial.println(F("ERRO ao gravar dados no ficheiro LOG!"));
  } 
}
void clienteLigado() {
  char clientline[BUFSIZ];
  char* ficheiroLer;
  int index = 0;
  Serial.println(F("variaveis feito"));
  client = server.available();
  Serial.println(F("client server available feito"));
  if (client) {
    Serial.println(F("Cliente ligado-------------------------"));
    index = 0;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
         if (c != '\n' && c != '\r') {
      clientline[index] = c;
      index++;
      if (index >= BUFSIZ) {
        index = BUFSIZ - 1;
        continue;
      }
         }
         clientline[index] = 0;
         Serial.println(clientline);
         digitalWrite(ledInfo, HIGH);
         delay(1);
         digitalWrite(ledInfo, LOW);
         
         if (strstr(clientline, "GET / ") != 0) {
           client.println("HTTP/1.1 200 OK");
           client.println("Content-Type: text/html");
           client.println();
           ficheiroLer = ficheiroIndex;
           lerFicheiroCartao();
         }
         else if (strstr(clientline, "GET /tanque") != 0) {
           client.println("HTTP/1.1 200 OK");
           client.println("Content-Type: image/jpeg");
           client.println();
           ficheiroLer = ficheiroTanque;
           lerFicheiroCartao();
         }
         else if (strstr(clientline, "GET /border") != 0) {
           client.println("HTTP/1.1 200 OK");
           client.println("Content-Type: image/jpeg");
           client.println();
           ficheiroLer = ficheiroBorder;
           lerFicheiroCartao();
         }
         else if (strstr(clientline, "GET /rodape") != 0) {
           client.println("HTTP/1.1 200 OK");
           client.println("Content-Type: image/jpeg");
           client.println();
           ficheiroLer = ficheiroRodape;
           lerFicheiroCartao();
         }
         else if (strstr(clientline, "GET /iframe") != 0) {
           client.println("HTTP/1.1 200 OK");
           client.println("Content-Type: text/html");
           client.println();
           ficheiroLer = ficheiroIframe;
           lerFicheiroCartao();
           client.println(F("<html><body>"));
           client.println(F("<div id=\"outer\">"));
           client.print(F("<div id=\"inner\" style=\"height:"));
           client.print(percentagem, 1);
           client.println(F("%\">"));
           client.println(F("</div></div>"));
           client.println(F("</p></body></html>"));
         }
         else if (strstr(clientline, "GET /2iframe") != 0) {
           client.println("HTTP/1.1 200 OK");
           client.println("Content-Type: text/html");
           client.println();
           ficheiroLer = ficheiro2Iframe;
           lerFicheiroCartao();
           client.println(F("<html><body>"));
           if (percentagem >= 90 || percentagem <=10){
              client.println(F("<table width=\"210\" height=\"42\" border=\"0\" cellpadding=\"1\" cellspacing=\"1\">"));
              client.println(F("<tr>"));
              client.print(F(" <td width=\"69\" height=\"40\" class=\"iframe2\"><div align=\"center\"><b><font color=#E60000>"));
              client.print(percentagem, 1);
              client.println(F("%</font></b></div></td>"));
              client.print(F("<td width=\"134\" class=\"iframe2\"><div align=\"center\"><b><font color=#E60000>"));
              client.print(litros);
              client.print(F("</font></b></div></td>"));
              client.println(F("</tr>"));
              client.println(F("</table>"));
              client.println(F("</p></body></html>"));
            } 
            else {
              client.println(F("<table width=\"210\" height=\"42\" border=\"0\" cellpadding=\"1\" cellspacing=\"1\">"));
              client.println(F("<tr>"));
              client.print(F(" <td width=\"69\" height=\"40\" class=\"iframe2\"><div align=\"center\"><b>"));
              client.print(percentagem, 1);
              client.println(F("%</b></div></td>"));
              client.print(F("<td width=\"134\" class=\"iframe2\"><div align=\"center\"><b>"));
              client.print(litros);
              client.print(F("</b></div></td>"));
              client.println(F("</tr>"));
              client.println(F("</table>"));
              client.println(F("</p></body></html>"));
            }
         }
         else if (strstr(clientline, "GET /&logg") != 0) {
           client.println("HTTP/1.1 200 OK");
           client.println("Content-Disposition: attachment; filename=\"Ficheiro_LOG_Tanque.txt\"");
           client.println();
           ficheiroLer = ficheiroLog;
           lerFicheiroCartao();
         }
         else {
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>Erro 404</h2>");
          client.println("<s2>O caminho ou ficheiro especificado nao existe.<s2>");
          client.println("");
         }
         break;
      }
    }
    digitalWrite(ledInfo, HIGH);
    delay(1);
    digitalWrite(ledInfo, LOW);
    delay(2);
    client.stop();
  }
  Serial.println(F("ClienteLigado Concluida"));
}

void lerFicheiroCartao() {
  boolean ficheiro = false;
  ficheiro = file.open(&root, ficheiroLer, O_READ);
  if (ficheiro) {
          byte clientBuf[64];
          int clientCount = 0;
          
          while(file.available()) {
            clientBuf[clientCount] = file.read();
            clientCount++;
            if (clientCount > 63) {
              client.write(clientBuf, 64);
              clientCount = 0;
            }
          }
            if (clientCount > 0) {
              client.write(clientBuf, clientCount);
            }
            file.close();
            ficheiroLer = '\0';
  }
  Serial.println(F("LerFicheiroCartao Concluida"));
}

Because the code is a little big i had to put it in two parts...
Many Serial.println was there for me to try to find the issue.
Many thanks in advance!

OK, i think this forum has good vibes! Meanwhile i've just discovered the issue... i have to put

EthernetServer server = EthernetServer(80);

and char* ficheiroLer;
must be a global variable because of lerFicheiroCartao(); function... but compiler doesn't give me any error code.
and now it is working... that part!

I'm experienced that when arduino is given the index.htm file and images it resets a lot of times, and some of them are not displayed on browser...

I'm having this on serial monitor...

Memoria RAM Livre: 284
O volume e FAT16

Ficheiros na raiz do cartao:
IFRAME.HTM     2013-02-04 17:01:50 816
INDEX.HTM      2013-03-11 17:19:04 10934
TANQUE.JPG     2013-01-30 17:23:20 73287
2IFRAME.HTM    2013-02-04 16:57:22 359
BORDER.JPG     2013-02-01 13:44:54 110590
&LOGG.TXT      2013-03-01 14:13:58 9338
FAVICON.ICO    2013-01-17 19:48:32 4150

Ficheiros encontrados em todos os directorios do cartao:
IFRAME.HTM
INDEX.HTM
TANQUE.JPG
2IFRAME.HTM
BORDER.JPG
&LOGG.TXT
FAVICON.ICO

Concluida a inicializacao do Cartao SD
Escrita do header no ficheiro LOG concluida!
Configuracao Concluida
GET P? Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida
GET / HTTP/1,\(                E,§   @G  Ãfiguracao Concluida?...Memoria RAM Livre: 284
O volume e FAT16

Ficheiros na raiz do cartao:
IFRAME.HTM     2013-02-04 17:01:50 816
INDEX.HTM      2013-03-11 17:19:04 10934
TANQUE.JPG     2013-01-30 17:23:20 73287
2IFRAME.HTM    2013-02-04 16:57:22 359
BORDER.JPG     2013-02-01 13:44:54 110590
&LOGG.TXT      2013-03-01 14:13:58 9384
FAVICON.ICO    2013-01-17 19:48:32 4150

Ficheiros encontrados em todos os directorios do cartao:
IFRAME.HTM
INDEX.HTM
TANQUE.JPG
2IFRAME.HTM
BORDER.JPG
&LOGG.TXT
FAVICON.ICO

Concluida a inicializacao do Cartao SD
Escrita do header no ficheiro LOG concluida!
Configuraciguracao Con

a

As you can see, Ethernet shield restarts a lot of time and browser stays like "thinking" and stays this for a long time...

If it restarts, then it has probably run out of SRAM. I recommend finishing what you apparently started, and use the F() function on all static strings. I see a bunch that are still not using the F() function.

every client.print ?

blastboot:
every client.print ?

Every Serial.print(), Serial.println(), Serial.write(), client.print(), client.println() and client.write() with a static string should use the F() function. Otherwise, those strings are copied into SRAM.

Thanks a lot! It worked and now my program works fine :smiley:

Another thing when i see "Memoria RAM Livre: 284" (equal to "Free RAM Memory: 284" when SD Card initializes, this tells that i have 284 bytes of RAM memory available or no?

blastboot:
Another thing when i see "Memoria RAM Livre: 284" (equal to "Free RAM Memory: 284" when SD Card initializes, this tells that i have 284 bytes of RAM memory available or no?

That sounds about right.

So why did it run out of memmory? (just to understand that :smiley: )

blastboot:
So why did it run out of memmory? (just to understand that :smiley: )

That part is easy! Count up all the characters in the client.print() and client.println() static strings that were not using the F() function. If that exceeded 284...crash!

So why did it run out of memmory?

It doesn't take a lot of string literals to eat up 284 bytes of SRAM.

got it! so that "free memmory" will be used by client.print and serial.print commands during it's loop... I thought that when we compile the program the compiler checks that :\