Tutorial del Internet de las Cosas y Bluetooth con el ESP32
Juan Antonio Villalpando
Volver al índice del tutorial
____________________________
147.- Wemos D1 R32 ESP32. App Inventor obtiene el estado de dos pulsadores. WiFi.
p147wemos_pulsadores.aia
- Pulsamos un Botón en App Inventor y obtenemos el estado de dos pulsadores.
_________________________________
- Diseño.

_________________________________
- Bloques.

_________________________________
- Conexiones.

_________________________________
- Código.
- Vamos a configurarlo con IP estática.
AI2_pulsadores.ino |
// Juan A. Villalpando.
// KIO4.COM
// Consulta el estado de los pulsadores.
#include <WiFi.h>
const char* ssid = "Nombre_de_tu_red_wifi";
const char* password = "La_clave_de_tu_red_wifi";
// Configuración de la IP estática.
IPAddress local_IP(192, 168, 1, 12);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8); //opcional
IPAddress secondaryDNS(8, 8, 4, 4); //opcional
#define pulsa16 16 // Pulsador en terminal 16.
#define pulsa17 17 // Pulsador en terminal 17.
int pulsador16;
int pulsador17;
String estado16;
String estado17;
String respuesta = "0,0";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
pinMode(pulsa16, INPUT);
pinMode(pulsa17, INPUT);
// Establecimiento de la IP estática.
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("Fallo en la configuración.");
}
// Conecta a la red wifi.
Serial.println();
Serial.print("Conectando con ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Conectado con WiFi.");
// Inicio del Servidor web.
server.begin();
Serial.println("Servidor web iniciado.");
// Esta es la IP
Serial.print("Esta es la IP para conectar: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
}
void loop() {
// Consulta si se ha conectado algún cliente.
WiFiClient client = server.available();
if (!client) {
return;
}
Serial.print("Nuevo cliente: ");
Serial.println(client.remoteIP());
// Espera hasta que el cliente envíe datos.
while(!client.available()){ delay(1); }
/////////////////////////////////////////////////////
// Lee la información enviada por el cliente.
String req = client.readStringUntil('\r');
Serial.println(req);
// Realiza la petición del cliente.
if (req.indexOf("estado") != -1){consulta();}
//////////////////////////////////////////////
// Página WEB. ////////////////////////////
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // Comillas importantes.
client.println(respuesta);
Serial.print("Cliente desconectado: ");
Serial.println(client.remoteIP());
client.flush();
client.stop();
}
// Consulta el estado de los elementos.
void consulta(){
pulsador16 = digitalRead(pulsa16);
if (pulsador16 == HIGH) {estado16 = "Pulsador16 PULSADO";} else {estado16 = "Pulsador16 NO pulsado";}
pulsador17 = digitalRead(pulsa17);
if (pulsador17 == HIGH) {estado17 = "Pulsador17 PULSADO";} else {estado17 = "Pulsador17 NO pulsado";}
respuesta = estado16 + "," + estado17;
Serial.println(respuesta);
delay(10);
}
|
- Este código es el mismo pero con comentarios en inglés.
AI2_pulsadores.ino |
// Juan A. Villalpando.
// KIO4.COM
// Estado de dos pulsadores
#include <WiFi.h>
const char* ssid = "Nombre_de_tu_red_wifi";
const char* password = "La_clave_de_tu_red_wifi";
// Setting Static IP.
IPAddress local_IP(192, 168, 1, 115);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8); //opcional
IPAddress secondaryDNS(8, 8, 4, 4); //opcional
WiFiServer server(80); // Port 80
#define pulsa16 16 // PushButton 16.
#define pulsa17 17 // PushButton 17.
String estado = "";
int wait30 = 30000; // time to reconnect when connection is lost.
void setup() {
Serial.begin(115200);
pinMode(pulsa16, INPUT);
pinMode(pulsa17, INPUT);
// Setting Static IP.
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("Error in configuration.");
}
// Connect WiFi net.
Serial.println();
Serial.print("Connecting with ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected with WiFi.");
// Start Web Server.
server.begin();
Serial.println("Web Server started.");
// This is IP
Serial.print("This is IP to connect to the WebServer: ");
Serial.print("http://");
Serial.println(WiFi.localIP());
}
void loop() {
// If disconnected, try to reconnect every 30 seconds.
if ((WiFi.status() != WL_CONNECTED) && (millis() > wait30)) {
Serial.println("Trying to reconnect WiFi...");
WiFi.disconnect();
WiFi.begin(ssid, password);
wait30 = millis() + 30000;
}
// Check if a client has connected..
WiFiClient client = server.available();
if (!client) {
return;
}
Serial.print("New client: ");
Serial.println(client.remoteIP());
// Espera hasta que el cliente envíe datos.
// while(!client.available()){ delay(1); }
/////////////////////////////////////////////////////
// Read the information sent by the client.
String req = client.readStringUntil('\r');
Serial.println(req);
// Make the client's request.
if (req.indexOf("consulta") != -1){
estado ="";
if (digitalRead(pulsa16) == HIGH) {estado = "PushBtn16 ON,";} else {estado = "PushBtn16 OFF,";}
if (digitalRead(pulsa17) == HIGH) {estado = estado + "PushBtn17 ON";} else {estado = estado + "PushBtn17 OFF";}
}
//////////////////////////////////////////////
// Página WEB. ////////////////////////////
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // Comillas importantes.
client.println(estado); // Return status.
client.flush();
client.stop();
Serial.println("Client disconnected.");
}
|
_________________________________
- Comentarios.
- ¿Cómo se obtiene por separado cada pulsador?
- ContenidodeRespuesta: Pulsador16 PULSADO,Pulsador17 NO PULSADO
- Lo guardamos en una tabla llamada respuesta, cada parte separada por coma es un elemento (esto lo hace el bloque lista desde registro csv)
respuesta |
1 |
Pulsador16 PULSADO |
2 |
Pulsador17 NO PULSADO |
- Ahora mostramos en las Etiquetas.Texto los elementos 1 y 2

________________________________
- Si en un navegador web escribimos:
192.168.1.12/estado
obtendremos el estado de los dos pulsadores.
- En el código del Arduino, las variables:
int pulsador16;
int pulsador17;
también las podríamos haber puesto de tipo bool.
bool pulsador16;
bool pulsador17;
_________________________________
_________________________________
_________________________________
_________________________________
- Con un Reloj.
- En vez de Pulsar el Botón para obtener el estado de los pulsadores, se obtendrá automáticamente mediante un Temporizador, Reloj.
p147wemos_pulsadores_Reloj.aia
_________________________________
- Diseño.
- En el Diseño añadimos un Reloj y le ponemos IntervaloDelReloj a 500.
- Cada 500 milisegundos, el Temporizador obtendrá el valor de la página web.
_________________________________
- Bloques.

_________________________________________________________

_______________________________
|