Possible cache problem?

Hi Guys! I have a strange problem... Using some examples, I've built a program that turn led's on or off using ATMEGA 328P + ESP8266 (Robotdyn).
The programs run well, but my "Desligar" button (turn off led) need to be clicked 2 times to work.
When I click in the 1st time, the browser url changes correctly to "/1/desligado" (for example) but I need to click one more time on same button for it works.

Here is my code on ESP8266:

#include <ESP8266WiFi.h>

// Substitua pelas suas credenciais de rede.
const char* ssid     = "*****";
const char* password = "****";

// Set your Static IP address
IPAddress local_IP(192, 168, 0, 88);
// Set your Gateway IP address
IPAddress gateway(192, 168, 0, 1);

IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);   //optional
IPAddress secondaryDNS(1, 1, 1, 1); //optional
 
// Defina um servidor com a porta 80.
WiFiServer server(80);
 
// Variável para armazenar a solicitação HTTP.
String header;
 
// Variável para armazenar o estado de saída atual.
String outputState1 = "Desligado";
String outputState2 = "Desligado";
String outputState3 = "Desligado";
 
unsigned long currentTime = millis();
unsigned long previousTime = 0;
// Defina um timeout de 2000 milisegundos.
const long timeoutTime = 2000;
 
void setup() {
  Serial.println(ssid);
  Serial.begin(9600);
  delay(5000);
  // Configures static IP address
  if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("STA Failed to configure");
  }
  // Conecte com a rede Wi-Fi com SSID e senha.
  Serial.print("Conectando a rede ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi conectado.");
  Serial.println("IP: ");
  Serial.println(WiFi.localIP());
  //Inicie o servidor.
  server.begin();
}

void loop() {
  WiFiClient client = server.available();   // Escute os clientes conectados 
  if (client) {                             // Se um novo cliente se conectar
    String currentLine = "";                // Faça uma String para armazenar dados recebidos do cliente
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop enquanto cliente estiver conectado.
      currentTime = millis();
      if (client.available()) {             // Se holver bytes para ler do cliente,
        char c = client.read();             // faça a leitura.
        header += c;
        if (c == '\n') {                    // Se o byte é um caractere de nova linha, 
                                            // é o fim da solicitação HTML,entao envie uma resposta.
          if (currentLine.length() == 0) {  
            //Envie um cabeçalho HTTP de resposta.
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            delay(50);
            // 1111111
            if (header.indexOf("/1/ligado") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED1_ON");
              //Serial.println("Estava: " + outputState1);
              //Altere a variavel de estado.
              outputState1 = "Ligado";
              Serial.println("Ficou: " + outputState1);
            } else if (header.indexOf("/1/desligado") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED1_OFF");
              //Serial.println("Estava: " + outputState1);
              //Altere a variavel de estado.
              outputState1 = "Desligado";
              Serial.println("Ficou: " + outputState1);
            }
            delay(50);
            // 22222222
            if (header.indexOf("/2/ligado") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED2_ON");
              //Serial.println("Estava: " + outputState2);
              //Altere a variavel de estado.
              outputState2 = "Ligado";
              Serial.println("Ficou: " + outputState2);
            } else if (header.indexOf("/2/desligado") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED2_OFF");              
              //Altere a variavel de estado.
              //Serial.println("Estava: " + outputState2);
              outputState2 = "Desligado";
              Serial.println("Ficou: " + outputState2);
            }
            delay(50);
            // 333333333333
            if (header.indexOf("/3/ligado") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED3_ON");
              //Serial.println("Estava: " + outputState3);              
              //Altere a variavel de estado.
              outputState3 = "Ligado";
              Serial.println("Ficou: " + outputState3);
            } else if (header.indexOf("/3/desligado") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED3_OFF");
              //Serial.println("Estava: " + outputState3);
              //Altere a variavel de estado.
              outputState3 = "Desligado";
              Serial.println("Ficou: " + outputState3);
            }
            delay(50);
            /*
            // 4444444444
            if (header.indexOf("GET /5/on") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED5_ON");
              //Altere a variavel de estado.
              outputState = "Ligado";
            } else if (header.indexOf("GET /5/off") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED5_OFF");
              //Altere a variavel de estado.
              outputState = "Desligado";
            }
            delay(50);
            // 555555555555
            if (header.indexOf("GET /6/on") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED6_ON");
              //Altere a variavel de estado.
              outputState = "Ligado";
            } else if (header.indexOf("GET /6/off") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED6_OFF");
              //Altere a variavel de estado.
              outputState = "Desligado";
            }
            delay(50);
            // 66666666666
            if (header.indexOf("GET /7/on") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED7_ON");
              //Altere a variavel de estado.
              outputState = "Ligado";
            } else if (header.indexOf("GET /7/off") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED7_OFF");
              //Altere a variavel de estado.
              outputState = "Desligado";
            }
            delay(50);
            // 777777777777777777
            if (header.indexOf("GET /9/on") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED9_ON");
              //Altere a variavel de estado.
              outputState = "Ligado";
            } else if (header.indexOf("GET /9/off") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED9_OFF");
              //Altere a variavel de estado.
              outputState = "Desligado";
            }
            delay(50);
            // 88888888888888888
            if (header.indexOf("GET /10/on") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED10_ON");
              //Altere a variavel de estado.
              outputState = "Ligado";
            } else if (header.indexOf("GET /10/off") >= 0) {
              //Envie um comando para Mega2560 via serial.
              Serial.println("LED10_OFF");
              //Altere a variavel de estado.
              outputState = "Desligado";
            } */
              header="";
              // Pagina HTML
              client.println("<!DOCTYPE html><html>");
              client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
              client.println("<link rel=\"icon\" href=\"data:,\">");
              // CSS para estilizar a pagina
              client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
              client.println("h1,p {font-weight: bold;color: #126e54; font-size: 32px;}");
              client.println("p {font-size: 16px;}");
              client.println(".button { background-color: #1BAE85; border: none; color: white; padding: 16px 40px;");
              client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
              client.println("</style></head>");
 
              client.println("<body><h1>DDS Picking by Cart</h1>");
 
              client.println("<p>Caixa 1 - Estado " + outputState1 + "</p>");
              
              if (outputState1 == "Desligado") {
                client.println("<p><a href=\"/1/ligado\"><button class=\"button\">Ligar</button></a></p>");
              } else if (outputState1 == "Ligado") {
                // Se outputState estiver como Ligado, crie um botao com texto Desligar.
                client.println("<p><a href=\"/1/desligado\"><button class=\"button button2\">Desligar</button></a></p>");
              }
              delay(50);

              client.println("<p>Caixa 2 - Estado " + outputState2 + "</p>");
              // Se outputState estiver como Desligado, crie um botao com texto Ligar.
              if (outputState2 == "Desligado") {
                client.println("<p><a href=\"/2/ligado\"><button class=\"button\">Ligar</button></a></p>");
              } else if (outputState2 == "Ligado") {
                // Se outputState estiver como Ligado, crie um botao com texto Desligar.
                client.println("<p><a href=\"/2/desligado\"><button class=\"button button2\">Desligar</button></a></p>");
              }
              delay(50);

              client.println("<p>Caixa 3 - Estado " + outputState3 + "</p>");
              // Se outputState estiver como Desligado, crie um botao com texto Ligar.
              if (outputState3 == "Desligado") {
                client.println("<p><a href=\"/3/ligado\"><button class=\"button\">Ligar</button></a></p>");
              } else if (outputState3 == "Ligado") {
                // Se outputState estiver como Ligado, crie um botao com texto Desligar.
                client.println("<p><a href=\"/3/desligado\"><button class=\"button button2\">Desligar</button></a></p>");
              }
              delay(50);
              client.println("</body></html>");
              // A resposta HTTP termina com outra linha em branco.
              client.println();
              break;
            } else { // Se você recebeu uma nova linha, limpe currentLine
              currentLine = "";
            }
          } else if (c != '\r') {  // Se você tiver mais alguma coisa além de um caractere de retorno de carro,
            currentLine += c;      // Adicione-o ao final do currentLine.
          }
        }
      }
      // Limpe a variável de cabeçalho
      header = "";
      // Feche a conexão.
      client.stop();
      delay(100);
    }
  }

And Here is my code on ATMEGA 328P:

//Declaração das constantes
const int led1 = 4;  
const int led2 = 5;
const int led3 = 6;
const int led4 = 5;
const int led5 = 6;
const int led6 = 7;
const int led7 = 9;
const int led8 = 10;
//Variável que conterá os estados do botão (0 LOW, 1 HIGH).
int estadoBotao = 0;
int estadoLed = 0;
 
String msg="";
  
//Método setup, executado uma vez ao ligar o Arduino.
void setup() {
  pinMode(led1,OUTPUT);  //Definindo pino digital 12 como de saída.
  pinMode(led2,OUTPUT);  //Definindo pino digital 12 como de saída.
  pinMode(led3,OUTPUT);  //Definindo pino digital 12 como de saída.
  Serial.begin(9600);
}
 
//Método loop, executado enquanto o Arduino estiver ligado.
void loop() {  

  if (Serial.available()) {
    //Leitura de um byte.
    char data = Serial.read();
    //Imprima o mesmo dado pela porta usb.
    //Acrescente o caractere recebido a string de mensagem.
    msg += data;
 
    if (data == 13) {//Limpa a string ao receber caractere CR(Carriage return).
      msg = "";
    }
    if (msg.indexOf("LED1_ON") > 0) {//Verifica a ocorrencia do trecho "LED_ON" na mensagem recebida.
      //Ative a saida.
      digitalWrite(led1, HIGH);
    }
    else if (msg.indexOf("LED1_OFF")> 0) {//Verifica a ocorrencia do trecho "LED_OFF" na mensagem recebida.
      //Desligue a saida.
      digitalWrite(led1, LOW);
    }
     if (msg.indexOf("LED2_ON") > 0) {//Verifica a ocorrencia do trecho "LED_ON" na mensagem recebida.
      //Ative a saida.
      digitalWrite(led2, HIGH);
    }
    else if (msg.indexOf("LED2_OFF")> 0) {//Verifica a ocorrencia do trecho "LED_OFF" na mensagem recebida.
      //Desligue a saida.
      digitalWrite(led2, LOW);
    }
    if (msg.indexOf("LED3_ON") > 0) {//Verifica a ocorrencia do trecho "LED_ON" na mensagem recebida.
      //Ative a saida.
      digitalWrite(led3, HIGH);
    }
    else if (msg.indexOf("LED3_OFF")> 0) {//Verifica a ocorrencia do trecho "LED_OFF" na mensagem recebida.
      //Desligue a saida.
      digitalWrite(led3, LOW);
    }
  }
  delay(50);
}

If I type in the browser, instead use button, it work's perfectly.

PS: ignore that I've coded for 8 led's, but implemented 3 at moment for testing.
PS2: I tried to use another browser and other pc.

Here are a few things I noted about your code.

  • You use delay(). This is generally a bad idea and you should try to unlearn the use of it. Unfortunately, it is used in many simple examples but is not good for more complex sketches. Have a look at the following example to learn how to control timing of parts of your code without stopping everything.

File -> Examples -> 02.Digital -> BlinkWithoutDelay.

  • Avoid programming in three languages. It makes your code hard to read and can stop others from helping you effectively.

  • Avoid unnecessary comments. If you need simple comment rewrite your code. Use comments for things that cannot be coded or that are not obvious.

  • The logic in your ATmega code is computationally wasteful. It compares the msg every time a new character arrives. Wait for the CR and then run the parsing only one time before you clear the msg. ( See your ESP code )

  • In the ESP8266 code you use currentLine and header for the same thing. You fill one but test the other.

Try for help Klaus! I'll try to optime the code and repost here in case of problems!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.