Display real time data from NodeMCU on Android device with HTML file saved on seperate file/library

Download, extract and save the following library in your Arduino libraries folder as given in the following image.

Now, upload the following program to your NodeMCU.

#include <MainPage.h>
#include <WiFiAccessPoint.h>

#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char *APSSID = "ESP8266-WEB-SERVER";
const char *APPSK = "123456789";

int t = 134;

AsyncWebServer server(80);
AsyncClient Client;

String processor(const String &var)
{
  Serial.println("In the processor function...");
  
  if(var == "TEMPERATURE")
  {
    return String(t); 
  }

  return String();
}

void setup() {
  Serial.begin(115200);
  WiFi.softAP(APSSID, APPSK);

  IPAddress IP = WiFi.softAPIP();
  Serial.println(IP);

  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request) {
    request -> send_P(200, "text/plain", String(t).c_str());
  });

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request -> send_P(200, "text/html", MAIN_page, processor);
  });

  server.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  t++;
  delay(1000);

  if(t > 1000)
  {
    t = 0;
  }
}

MainPage.h

#ifndef MAINPAGE_H
#define MAINPAGE_H

const char MAIN_page[] PROGMEM = R"=====(

  <!DOCTYPE HTML><html>
    <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <H3>
          WELCOME TO ESP8266 WEB SERVER
       </H3>
       
       <H3>
          Value of T = 
          <span id="temperature">%TEMPERATURE%</span>
       </H3>
    </body>
    
    <script>
      setInterval(function ( ) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById("temperature").innerHTML = this.responseText;
          }
        };
        xhttp.open("GET", "/temperature", true);
        xhttp.send();
      }, 100 ) ;
    </script>
  </html>

)=====";

#endif

Watch the video demonstration to display the real time data from NodeMCU on Android device.

Published by

Leave a Reply

X