|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
  Raspberry Pi Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  AutoIt (Programación) Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


.

Tutorial del Internet de las Cosas y Bluetooth con el ESP32
Juan Antonio Villalpando

Volver al índice del tutorial

____________________________

249.- ESP32 - Envío de datos en tiempo real. WiFi. App Inventor. Visor Web.

- Vamos a enviar información desde el ESP32 a una página web y a una aplicación realizada con App Inventor mediante WiFi en tiempo real (aunque con un breve retardo).

- Modificaremos los códigos de esta página:

https://circuits4you.com/2018/11/20/web-server-on-esp32-how-to-update-and-display-sensor-values/

- Podemos hacer varias pruebas, enviar números aleatorios cada cierto tiempo, incrementar un número y enviarlo,...

- Pero en mi ejemplo utilizaremos el Monitor Serie, escribimos un número en el Monitor Serie y lo enviamos a una página web y a una aplicación de App Inventor.

__________________________________________________

- Código para el ESP32.

- En la parte del loop(), he puesto un código. Al escribir un texto en el Monitor Serie, se envía al archivo index.h

ESP32_realtime.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     = "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
 // int 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 = "";
      }
}
/////////////////////////////////////////////////////
}

- El código necesita dos archivos. Para añadir el archivo index.h vamos a Programa / Añadir fichero... y creamos el index.h

- Estos dos archivos se encontrarán en la carpeta del proyecto.

- En el archivo index.h observamos un retardo de 2000, si queremos menos tiempo, cambiamos ese número.

- Para enviar el resultado a la aplicación utilizamos la línea:

window.AppInventor.setWebViewString("" + this.responseText); // RESPUESTA A CadenaDeWebView

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>
)=====";

__________________________________________________

248.- ESP32 envia datos en tiempo real a la aplicación.

p248_esp32_realtime.aia

_________________
- Diseño.

_________________
- Bloques.

_____________________________________________________

_____________________________________________________

2.- ESP32 envia datos en tiempo real a la aplicación. Visualización en un gráfico dinámico.

p248_esp32_realtime_dynamic.aia

- En este tutorial sobre App Inventor vimos una extensión para dibujar un gráfico dinámico en la aplicación.

appinventor/299H_extension_GraficoDinamico.htm

- Se irá dibujando la función y desplazándose a la izquierda.

__________________________________________________

- Código para el ESP32.

- He cambiado:


int a = 0;

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
}

- En el archivo index.h he cambiado el tiempo, lo he puesto a 1000

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

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 = "";
      }
}
/////////////////////////////////////////////////////
}

_________________
- Diseño.

_________________
- Bloques.

_____________________________________________________

_____________________________________________________

- Otro código similar.

https://circuitdigest.com/microcontroller-projects/ajax-with-esp8266-dynamic-web-page-update-without-reloading

ESP32_realtime_3.ino


/*Arduino  code for ESP8266 AJAX Webserver
www.circuitdigest.com 
*/

// #include <ESP8266WiFi.h>
#include <WiFi.h>
#include <WiFiClient.h>
// #include <ESP8266WebServer.h>
#include <WebServer.h>
#include "index.h"
// #define LED D0
#define LED 4

const char* ssid     = "Red_WiFi";
const char* password = "Contraseña";
// ESP8266WebServer server(80);
WebServer server(80);

void handleRoot() 
{
 String s = webpage;
 server.send(200, "text/html", s);
}

void sensor_data() 
{
 // int a = analogRead(A0);
 int a = random(0,100);
 int temp= a/4.35;
 String sensor_value = String(temp);
 server.send(200, "text/plane", sensor_value);
}

void led_control() 
{
 String state = "OFF";
 String act_state = server.arg("state");
 if(act_state == "1")
 {
  digitalWrite(LED,HIGH); //LED ON
  state = "ON";
 }
 else
 {
  digitalWrite(LED,LOW); //LED OFF
  state = "OFF";
 }
 
 server.send(200, "text/plane", state);
}

void setup(void)
{
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");
  pinMode(LED,OUTPUT); 
  
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print("Connecting...");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
 
  server.on("/", handleRoot);
  server.on("/led_set", led_control);
  server.on("/adcread", sensor_data);
  server.begin();
}

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

index.h


const char webpage[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<style type="text/css">
.button {
  background-color: #4CAF50; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
</style>
<body style="background-color: #f9e79f ">
<center>
<div>
<h1>AJAX BASED ESP8266 WEBSERVER</h1>
  <button class="button" onclick="send(1)">LED ON</button>
  <button class="button" onclick="send(0)">LED OFF</button><BR>
</div>
 <br>
<div><h2>
  Temp(C): <span id="adc_val">0</span><br><br>
  LED State: <span id="state">NA</span>
</h2>
</div>
<script>
function send(led_sts) 
{
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("state").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "led_set?state="+led_sts, true);
  xhttp.send();
}
setInterval(function() 
{
  getData();
}, 2000); 
function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("adc_val").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "adcread", true);
  xhttp.send();
}
</script>
</center>
</body>
</html>
)=====";

 

 

_______________________________

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información