Hi Rui,
Finally, I just finish your book project of ESP8266 Web Server using SPIFFS and this is what I need. Thank you for this great book.
However, I need a further example regarding external output. In your example, we turn on/off the led through a web browser and the STATE will be displayed as well. Now, I add a real physical button that connected to NodeMCU to turn on/off the led as well. My question is how to make this physical button triggers the web site so the web page, as well as the STATE, will be changed accordingly. If the physical button is on, then the page will be 192.168.1.24/on and STATE is on. And if the button is off then the page will be 192.168.1.24/off and STATE is off.
I wish you can help me and many thanks in advance.
Hi.
I think what you need to do is creating a variable that holds the current output state. That variable can be changed either when you control the LED via web server, or when you press the physical button.
In the SPIFFS web server, there’s a placeholder to show the current state of the output. The placeholder should be replaced by the variable that holds the output state (ledState). Then, if we want the state to change automatically as the temperature and humidity do on the web server, we need to change some things.
For example, in the HTML file, you’ll need to add an ID to the output state:
<p><span id = "gpiostate"> GPIO state<strong> %STATE%</strong></span></p>
Then, between the <script> tags, add something as follows:
setInterval(function ( ) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("gpiostate").innerHTML = this.responseText; } }; xhttp.open("GET", "/gpiostate", true); xhttp.send(); }, 10000 ) ;
This will automatically make a request every second on the /gpiostate URL.
Then, in your code handle what happens when you receive a request on the /gpiostate
server.on("/gpiostate", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", gpiostate().c_str());
});
Also, don’t forget to change the ledState variable when you change the led state via web server. For example:
server.on("/on", HTTP_GET, [](AsyncWebServerRequest *request){
digitalWrite(ledPin, HIGH);
ledState = "ON";
request->send(SPIFFS, "/index.html", String(), false, processor);
});
I haven’t tested this, but I think it should work. I hope this helps.
Regards,
Sara