ESP32 sends data to the app over WiFi in realtime. JavaScript (ajax)

Hello friends,

this topic is about sending data from an ESP32 to the application via WiFi in real time. To send the data we will use the Serial Monitor.

/*
 * ESP32 AJAX Demo
 * Updates and Gets data from webpage without page refresh
 * https://circuits4you.com
 */
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

#include "index.h"  //Web page header file

WebServer server(80);

//Enter your SSID and PASSWORD
const char* ssid     = "YOUR_NETWORK";
const char* password = "YOUR_PASSWORD";

char caracter = '0';
String texto = "";
String texto_send = "";

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
 String s = MAIN_page; //Read HTML contents
 server.send(200, "text/html", s); //Send web page
}
 
void handleADC() {
 // int a = 0;
 // a = analogRead(A0);      // ORIGINAL CODE
 // a = random(1,1023);      // RANDOM NUMBER
 // a = a + 1;                        // INCREASE
 // if (a >= 1024){a = 0;}
 // String adcValue = String(a);
String adcValue = texto_send; // SEND TEXT FROM SERIAL MONITOR.
 server.send(200, "text/plane", adcValue); //Send ADC value only to client ajax request
}

//===============================================================
// Setup
//===============================================================

void setup(void){
  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting Sketch...");

/*
//ESP32 As access point
  WiFi.mode(WIFI_AP); //Access Point mode
  WiFi.softAP(ssid, password);
*/
//ESP32 connects to your wifi -----------------------------------
  WiFi.mode(WIFI_STA); //Connectto your wifi
  WiFi.begin(ssid, password);

  Serial.println("Connecting to ");
  Serial.print(ssid);

  //Wait for WiFi to connect
  while(WiFi.waitForConnectResult() != WL_CONNECTED){      
      Serial.print(".");
    }
    
  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
//----------------------------------------------------------------
 
  server.on("/", handleRoot);      //This is display page
  server.on("/readADC", handleADC);//To get update of ADC Value only
 
  server.begin();                  //Start server
  Serial.println("HTTP server started");
}

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void loop(void){
  server.handleClient();
  
//////////////// TEXT FROM SERIAL MONITOR  ////////////
  if (Serial.available() > 0) { // ¿Hay algún caracter?
      caracter = Serial.read(); // Toma el caracter
      texto += caracter;
      
      if (caracter == '\n') {
      texto_send = texto;
      Serial.println("Write a text in Serial Monitor and 'Send'");
      Serial.print(texto);
      texto = "";
      }
}
/////////////////////////////////////////////////////
}
  • The code also needs to include another file: index.h
2 Likes
  • File index.h

esp32_realtime1

esp32_realtime2

  • We Add the file ... index.h
const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<style>
.card{
    max-width: 400px;
     min-height: 250px;
     background: #02b875;
     padding: 30px;
     box-sizing: border-box;
     color: #FFF;
     margin:20px;
     box-shadow: 0px 2px 18px -4px rgba(0,0,0,0.75);
}
</style>
<body>

<div class="card">
  <h4>The ESP32 Update web page without refresh</h4><br>
  <h1>Sensor Value: <span id="ADCValue">0</span></h1><br>
  <br><a href="https://circuits4you.com">Circuits4you.com</a>
</div>
<script>

setInterval(function() {
  // Call a function repetatively with 2 Second interval
  getData();
}, 2000); //2000mSeconds update rate // HERE DELAY

function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("ADCValue").innerHTML =
      this.responseText;
      window.AppInventor.setWebViewString("" + this.responseText);  // RESPUESTA A CadenaDeWebView
    }
  };
  xhttp.open("GET", "readADC", true);
  xhttp.send();
}
</script>
</body>
</html>
)=====";
  • In that file we observe that a time of 2000 ms has been established.

  • We also observe the following line:

    window.AppInventor.setWebViewString("" + this.responseText);

  • this is to send the data to the app through the WebViewer component and JavaScript.

1 Like

- App Inventor.

p248i_esp32_realtime.aia (1.9 KB)

- Blocks.

esp32_realtime8i

1 Like

- Another images.

  • Write in Serial Monitor.

  • Obtaining data in real time (with a small delay) in Label1 and in WebViewer.

This guide in Spanish:
http://kio4.com/arduino/249_Wemos_TiempoReal_AI2.htm

2 Likes

2.- Another example. ESP32 increments a variable and is displayed in a dynamic graph in the app.

  • To create the dynamic graphic that scrolls to the left, we will use this extension:
    • Here the code in file ESP32_realtime_2.ino
/*
 * ESP32 AJAX Demo
 * Updates and Gets data from webpage without page refresh
 * https://circuits4you.com
 */
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

#include "index.h"  //Web page header file

WebServer server(80);

//Enter your SSID and PASSWORD
const char* ssid     = "Red_Wifi";
const char* password = "Contraseña";

char caracter = '0';
String texto = "";
String texto_send = "";
int a = 0;

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
 String s = MAIN_page; //Read HTML contents
 server.send(200, "text/html", s); //Send web page
}
 
void handleADC() {
 // a = analogRead(A0);      // ORIGINAL CODE
 // a = random(1,1023);      // RANDOM NUMBER
 a = a + 100;                // INCREASE
 if (a >= 1024){a = 0;}
String adcValue = String(a);
// String adcValue = texto_send; // SEND TEXT FROM SERIAL MONITOR.
 server.send(200, "text/plane", adcValue); //Send ADC value only to client ajax request
}

//===============================================================
// Setup
//===============================================================

void setup(void){
  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting Sketch...");

/*
//ESP32 As access point
  WiFi.mode(WIFI_AP); //Access Point mode
  WiFi.softAP(ssid, password);
*/
//ESP32 connects to your wifi -----------------------------------
  WiFi.mode(WIFI_STA); //Connectto your wifi
  WiFi.begin(ssid, password);

  Serial.println("Connecting to ");
  Serial.print(ssid);

  //Wait for WiFi to connect
  while(WiFi.waitForConnectResult() != WL_CONNECTED){      
      Serial.print(".");
    }
    
  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
//----------------------------------------------------------------
 
  server.on("/", handleRoot);      //This is display page
  server.on("/readADC", handleADC);//To get update of ADC Value only
 
  server.begin();                  //Start server
  Serial.println("HTTP server started");
}

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void loop(void){
  server.handleClient();
  
//////////////// TEXT FROM SERIAL MONITOR  ////////////
  if (Serial.available() > 0) { // ¿Hay algún caracter?
      caracter = Serial.read(); // Toma el caracter
      texto += caracter;
      
      if (caracter == '\n') {
      texto_send = texto;
      Serial.println("Write a text in Serial Monitor and 'Send'");
      Serial.print(texto);
      texto = "";
      }
}
/////////////////////////////////////////////////////
}
  • In the index.h file we change the delay to 1000.

}, 1000); //1000mSeconds update rate // HERE DELAY

- App.

p248_esp32i_realtime_dynamic.aia (10.3 KB)

- Blocks.

extension_graficodinamico23i

Thanks for the great tutorial.
may I know how to forward the local_IP address to the MIT APP, just like the 'texto' sent in your code please?
Best
Adam

I don't understand the question, do you mean to do a "port forwarding"?

1 Like

Thank you Juan.

I mean the ESP32 send IP address like: 192.168.1.12 - the four group numbers to MIT APP phone screen just like the " 45.78 " sent and received by screen.

Best.

Serial.println(WiFi.localIP()); //IP address assigned to your ESP

1 Like

Thank you, Juan.
I added the line to sketch #1:

  if (Serial.available() > 0) { // ¿Hay algún caracter?
      caracter = Serial.read(); // Toma el caracter
      texto += caracter;
      
      if (caracter == '\n') {
      texto_send = texto;
      Serial.println("Write a text in Serial Monitor and 'Send'");
      Serial.println(WiFi.localIP()); //IP address assigned to your ESP
      Serial.print(texto);
      texto = "";
    
      }
}

and it prints the IP address (192.168.4.320) to the serial monitor window on the pc instead of the phone screen.

when I typed in: 192.168.4.3 esp32 does send that to phone screen.

Try

if (caracter == '\n') {
      texto_send = texto;
      Serial.println("Write a text in Serial Monitor and 'Send'");
      Serial.println(WiFi.localIP()); //IP address assigned to your ESP
      //Serial.print(texto);
      texto = "";
1 Like

Thank you Juan.
I did the IP to String and sign the result to texto _send done the job.

 textIP = WiFi.localIP().toString().c_str();
  server.send(200, "text/plane", textIP); 

question is the ESP32 don't send till the typing, I'd like it send IP address as long as the ESP32 got the localIP. any idea please?

Best

Good example code Juan. thank you.

I wont to know how I can use with out side a local area net work, like somewhere far from the location of the ESP.
Could you please tell me some options for it?

Look for information about opening ports on the router, port forward.

https://portforward.com/how-to-port-forward/