How to change state on Wemos D1 while pressing html button

I am new in arduino. I am writing html page with two button. These two buttons are changing the global variable "count". I write a function for checking the count status and making a for loop to print something 10 times.
I would like to write a program to break the loop and change to another loop while pressing the html button

This is my program. When I pressed the html button, the Wemos reboot immediately and cannot change the state. anything wrong on my program??? please help me know

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-web-server-outputs-momentary-switch/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

#ifdef ESP32
  #include <WiFi.h>
  #include <AsyncTCP.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "***";
const char* password = "***";

const int output = 2;
int count = 0;
// HTML web page
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
  <head>
    <title>ESP Pushbutton Web Server</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      body { font-family: Arial; text-align: center; margin:0px auto; padding-top: 30px;}
      .button {
        padding: 10px 20px;
        font-size: 24px;
        text-align: center;
        outline: none;
        color: #fff;
        background-color: #2f4468;
        border: none;
        border-radius: 5px;
        box-shadow: 0 6px #999;
        cursor: pointer;
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        -webkit-tap-highlight-color: rgba(0,0,0,0);
      }  
      .button:hover {background-color: #1f2e45}
      .button:active {
        background-color: #1f2e45;
        box-shadow: 0 4px #666;
        transform: translateY(2px);
      }
    </style>
  </head>
  <body>
    <h1>ESP Pushbutton Web Server</h1>
    <button class="button" onmouseup="toggleCheckbox('mode1');" ontouchend="toggleCheckbox('mode1');">
      LED MODE 1
    </button>
    <button class="button" onmouseup="toggleCheckbox('mode2');" ontouchend="toggleCheckbox('mode2');">
      LED MODE 2
    </button>
   <script>
   function toggleCheckbox(x) {
     var xhr = new XMLHttpRequest();
     xhr.open("GET", "/" + x, true);
     xhr.send();
   }
  </script>
  </body>
</html>)rawliteral";

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

AsyncWebServer server(80);

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Failed!");
    return;
  }
  Serial.println();
  Serial.print("ESP IP Address: http://");
  Serial.println(WiFi.localIP());
  
  pinMode(output, OUTPUT);
  digitalWrite(output, LOW);
  
  // Send web page to client
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html);
  });

  // Receive an HTTP GET request
  server.on("/mode1", HTTP_GET, [] (AsyncWebServerRequest *request) {
    checkBtn(0);
    request->send(200, "text/plain", "ok");
  });

  // Receive an HTTP GET request
  server.on("/mode2", HTTP_GET, [] (AsyncWebServerRequest *request) {
    checkBtn(1);
    request->send(200, "text/plain", "ok");
  });
  
  server.onNotFound(notFound);
  server.begin();

  
}

void loop() {
}
void checkBtn(int count){
  Serial.print("-------count: ");
  Serial.println(count);
  int previousMillis = millis();
  int loopCount=0;
  if (count == 0){
    while(loopCount<10){
      if (millis() - previousMillis >1000){
        if (!chkState(count))
          break;
        Serial.print("case0: ");
        Serial.println(millis());
        previousMillis = millis();
        loopCount+=1;
      }
    }
  }
  else if(count == 1){
    while(loopCount<10){
      if (millis() - previousMillis >1000){
        if (!chkState(count))
          break;
        Serial.print("!case1!: ");
        Serial.println(millis());
        previousMillis = millis();
        loopCount+=1;
      }
    }
  }
}
bool chkState(int a){
  if (a == count)
    return true;
  else
    return false;
}

You may be getting a watchdog timer reset since your chkbtn() function runs so long. It would be much better to refactor your code to just set a flag on reception of the HTML request and then process the flag in your loop() function.

You also never, ever set the value of the global count (it is always 0) so what is the point? Don't confuse the global variable 'count' with the parameter 'count' that is passed into the chkbtn() function. Two completely different variables but humans sometimes mistakenly think they are the same. The compiler doesn't make that mistake.

Thanks for your comment. I rewrite my code. would you mind have a look on it?? is it a good practice for setting two global variable {curState, prevState} to keep checking the state?? Or is there any function can do the same thing??

#ifdef ESP32
  #include <WiFi.h>
  #include <AsyncTCP.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "***";
const char* password = "***";

int curState = 0;
int prevState = 0;
// HTML web page
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
  <head>
    <title>ESP Pushbutton Web Server</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      body { font-family: Arial; text-align: center; margin:0px auto; padding-top: 30px;}
      .button {
        padding: 10px 20px;
        font-size: 24px;
        text-align: center;
        outline: none;
        color: #fff;
        background-color: #2f4468;
        border: none;
        border-radius: 5px;
        box-shadow: 0 6px #999;
        cursor: pointer;
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        -webkit-tap-highlight-color: rgba(0,0,0,0);
      }  
      .button:hover {background-color: #1f2e45}
      .button:active {
        background-color: #1f2e45;
        box-shadow: 0 4px #666;
        transform: translateY(2px);
      }
    </style>
  </head>
  <body>
    <h1>ESP Pushbutton Web Server</h1>
    <button class="button" onmouseup="toggleCheckbox('state1');" ontouchend="toggleCheckbox('mode1');">
      LED MODE 1
    </button>
    <button class="button" onmouseup="toggleCheckbox('state2');" ontouchend="toggleCheckbox('mode2');">
      LED MODE 2
    </button>
   <script>
   function toggleCheckbox(x) {
     var xhr = new XMLHttpRequest();
     xhr.open("GET", "/" + x, true);
     xhr.send();
   }
  </script>
  </body>
</html>)rawliteral";

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

AsyncWebServer server(80);

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Failed!");
    return;
  }
  Serial.println();
  Serial.print("ESP IP Address: http://");
  Serial.println(WiFi.localIP());
  
  
  // Send web page to client
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html);
  });

  // Receive an HTTP GET request
  server.on("/state1", HTTP_GET, [] (AsyncWebServerRequest *request) {
    curState = 0;
    request->send(200, "text/plain", "ok");
  });

  // Receive an HTTP GET request
  server.on("/state2", HTTP_GET, [] (AsyncWebServerRequest *request) {
    curState = 1;
    request->send(200, "text/plain", "ok");
  });
  
  server.onNotFound(notFound);
  server.begin();

  
}

void loop() {
  if (curState == 0){
    for(int i=0; i< 10; i++){
      if (prevState != curState){
        prevState = curState;  
        break;
      }
      Serial.print("case0: ");
      Serial.println(i);
      delay(1000);
    }
  }
  else if(curState ==1){
    for(int i=20; i< 30; i++){
      if (prevState != curState){
        prevState = curState;  
        break;
      }
      Serial.print("case1: ");
      Serial.println(i);
      delay(1000);
    }
  }
}

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