Automatic Refresh/Reolad of WebServer with NodeMCU (ESP8266)

I coded a very simple Web Server, that performs a sort of counter. Every time I refresh manually the page the next number is displayed in the Web Server.

This is the basic code:

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

#ifndef STASSID
#define STASSID "*********"
#define STAPSK   "*********"
#endif

ESP8266WebServer server(80);
const char* ssid = STASSID;
const char* password = STAPSK;


int a = 1;


void setup() {
WiFi.begin(ssid,password);
Serial.begin(9600);
while(WiFi.status()!=WL_CONNECTED) {
  Serial.print(".");
  delay(500);
  }
Serial.println("");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());

server.on("/", counter);
server.begin();
}


void loop() {
server.handleClient();   //main function
}


void counter() {
a++;
Serial.println(a);
delay(1000);

String output = String(a);
server.send(200,"text/plain", output);
  }

My question is: How can I make refresh the Web Server in automatic in the easiest way possible? For examaple, every two seconds refresh the page...
What do I need to add in this code to make this work?

I can't find in the web other complete examples of this topic.

I've found this great tutorial on autoupdate Web Server for ESP8266. Check it out

http://www.martyncurrey.com/esp8266-and-the-arduino-ide-part-8-auto-update-webpage/

1 Like

I'm sending Humidity data from a sensor (DHT11) to a NodeMCU (ESP8266). I'm sending this data through ArduinoJSON library and this is working perfect. So the NodeMCU can Deserialize with no problem the JSON object and read it, and send it to the WebServer.
This below is the code of the NodeMCU:

/*------------------------------------------------------------------------------
  06/25/2019
  Author: Makerbro
  Platforms: ESP8266
  Language: C++/Arduino
  File: esp8266_firmware.ino
  ------------------------------------------------------------------------------
  Description:
  Code for YouTube video demonstrating how to communicate between an Arduino UNO
  and an ESP8266.
  https://youtu.be/6-RXqFS_UtU

  Do you like my videos? You can support the channel:
  https://patreon.com/acrobotic
  https://paypal.me/acrobotic
  ------------------------------------------------------------------------------
  Please consider buying products from ACROBOTIC to help fund future
  Open-Source projects like this! We'll always put our best effort in every
  project, and release all our design files and code for you to use.

  https://acrobotic.com/
  https://amazon.com/acrobotic
  ------------------------------------------------------------------------------
  License:
  Please see attached LICENSE.txt file for details.
  ------------------------------------------------------------------------------*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>

#ifndef STASSID
#define STASSID "********"
#define STAPSK  "********"
#endif

ESP8266WebServer server(80);
const char* ssid = STASSID;
const char* password = STAPSK;



void setup()
{
  WiFi.begin(ssid, password);
  Serial.begin(9600);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handleIndex);
  server.begin();
}

void loop()
{
  server.handleClient();
}

void handleIndex()
{
  // Send a JSON-formatted request with key "type" and value "request"
  // then parse the JSON-formatted response with keys "gas" and "distance"
  DynamicJsonDocument doc(1024);
  float Humidity = 0;
  // Sending the request
  doc["type"] = "request";
  serializeJson(doc, Serial);
  // Reading the response
  boolean messageReady = false;
  String message = "";
  while (messageReady == false) { // blocking but that's ok
    if (Serial.available()) {
      message = Serial.readString();
      messageReady = true;
    }
  }
  // Attempt to deserialize the JSON-formatted message
  DeserializationError error = deserializeJson(doc, message);
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }
  Humidity = doc["Humidity"];
  // Prepare the data for serving it over HTTP
  String output = "Humidity: " + String(Humidity);
  // Serve the data as plain text, for example
  server.send(200, "text/plain", output);
}

I found a way to autorefresh the WebServer every x second in the tutorial I showed in the previous message, and this is working perfect. So I can see a page where there's a sort of counter.

But when I try to send the JSON data in the new code where I want to refresh the page, let's say every 5 seconds, the JSON desirialization it gives me back the error: Invalid Input multiple times. So because this is given multiple times I think that the part of the autorefresh of the WebServer is working, but for some reason the JSON part has conflict with the autorefresh part of the WebServer.

The first two codes worked well.

This is the last code, the one that doesn't work:

//http://www.martyncurrey.com/esp8266-and-the-arduino-ide-part-8-auto-update-webpage/
/*
 * Sketch: ESP8266_Part8_01_AutoUpdate_HTML
 * Intended to be run on an ESP8266
 */
 
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
 
String html_1 = R"=====(
<!DOCTYPE html>
<html>
 <head>
 <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
 <meta charset='utf-8'>
 <meta http-equiv='refresh' content='5'>
 <style>
   body {font-size:100%;} 
   #main {display: table; margin: auto;  padding: 0 10px 0 10px; } 
   h2 {text-align:center; } 
   p { text-align:center; }
 </style>
   <title>Auto Update Example Using HTML</title>
 </head>
 
 <body>
   <div id='main'>
     <h2>Auto Update Example Using HTML</h2>
     <div id='count'> 
       <p>Count = %Humidity%</p>
     </div>
   </div> 
 </body>
</html>
)====="; 
 
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
 
// change these values to match your network
char ssid[] = "*********";       //  your network SSID (name)
char pass[] = "********";          //  your network password

WiFiServer server(80);

String tmpString = "";
unsigned int count = 0; 
 
void setup() 
{
    Serial.begin(9600);
    Serial.println();
    Serial.println("Serial started at 115200");
    Serial.println();
 
    // Connect to a WiFi network
    Serial.print(F("Connecting to "));  Serial.println(ssid);
    WiFi.begin(ssid, pass);
 
    while (WiFi.status() != WL_CONNECTED) 
    {
        Serial.print(".");
        delay(500);
    }
 
    Serial.println("");
    Serial.println(F("[CONNECTED]"));
    Serial.print("[IP ");              
    Serial.print(WiFi.localIP()); 
    Serial.println("]");
 
    // start a server
    server.begin();
    Serial.println("Server started");
 
} // void setup()
 
void loop() 
{

// Send a JSON-formatted request with key "type" and value "request"
  // then parse the JSON-formatted response with keys "gas" and "distance"
  DynamicJsonDocument doc(1024);
  float Humidity = 0; 
  // Sending the request
  doc["type"] = "request";
  serializeJson(doc, Serial);
  // Reading the response
  boolean messageReady = false;
  String message = "";
  while (messageReady == false) { // blocking but that's ok
    if (Serial.available()) {
      message = Serial.readString();
      messageReady = true;
    }
  }
  // Attempt to deserialize the JSON-formatted message
  DeserializationError error = deserializeJson(doc, message);
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }
  
  Humidity = doc["Humidity"];
  Serial.print("Humidity = "); 
  Serial.println(Humidity); 

delay(2000);

  Serial.println("Entering the Client part");
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client)  {  return;  }
 



  // Prepare the data for serving it over HTTP
    

    tmpString = html_1;
    tmpString.replace("%Humidity%", String(Humidity) );
 
    client.flush();
    client.print( header );
    client.print( tmpString );  
     
    
        
 
    delay(100);
 
 
  // The client will actually be disconnected when the function returns and 'client' object is destroyed
} // void loop()

Can someone see this conflict in these two part of the code?
How can I fix this?
Any suggestion are welcomed.

Any feedback on why the JSON part has conflict with the Web Server one? I'm not asking for the solution, just a feedback and where to look to make the things work. Thank You

1 Like