Tutorial del Internet de las Cosas y Bluetooth con el ESP32
Juan Antonio Villalpando
Volver al índice del tutorial
____________________________
125.- Wemos D1 R32 ESP32. App Inventor enciende/apaga LED.
_________________________________
16.- WiFi. App Inventor. App Inventor enciende/apaga LED.
p125wemos_led.aia
- Al pulsar los Botones de la aplicación apagamos y encendemos dos LED de la tarjeta.
_________________________________
- Diseño.
_________________________________
- Bloques.
_________________________________
- Código.
- Vamos a configurarlo con IP estática.
AI2_LED.ino |
// Juan A. Villalpando.
// KIO4.COM
// Pone los LED12 y LED14 en alto o bajo.
#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 LED12 12 // LED en terminal 12
#define LED14 14 // LED en terminal 14
WiFiServer server(80);
void setup() {
Serial.begin(115200);
pinMode(LED12, OUTPUT);
pinMode(LED14, OUTPUT);
// 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.println(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("on12") != -1) {digitalWrite(LED12, HIGH);}
if (req.indexOf("off12") != -1){digitalWrite(LED12, LOW);}
if (req.indexOf("on14") != -1) {digitalWrite(LED14, HIGH);}
if (req.indexOf("off14") != -1){digitalWrite(LED14, LOW);}
//////////////////////////////////////////////
// Página WEB. ////////////////////////////
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // Importante.
Serial.print("Cliente desconectado: ");
Serial.println(client.remoteIP());
client.flush();
client.stop();
}
|
___________________________________________________
- Comentarios.
- Mediante estas órdenes el código comprueba si el texto recibido contiene on12, off12, on14 o off14
req.indexOf("on12") != -1)
req.indexOf("off12") != -1)
req.indexOf("on14") != -1)
req.indexOf("off14") != -1)
___________________________________________________
___________________________________________________
___________________________________________________
- Obtención de respuesta.
p125wemos_led_B.aia
- En este caso después de pulsar y encender/apagar el LED, el código envía una respuesta.
- Añade una Etiqueta2 al Diseño de App Inventor
_________________________________
- Bloques.
_________________________________
- Código.
- Vamos a configurarlo con IP estática.
AI2_LED_respuesta.ino |
// Juan A. Villalpando.
// KIO4.COM
// Pone los LED12 y LED14 en alto o bajo.
#include <WiFi.h>
const char* ssid = "Nombre_red_WiFi";
const char* password = "contraseña_red";
// 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 LED12 12 // LED en terminal 12
#define LED14 14 // LED en terminal 14
String respuesta= "";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
pinMode(LED12, OUTPUT);
pinMode(LED14, OUTPUT);
// 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.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());
Serial.println("/");
}
void loop() {
// Consulta si se ha conectado algún cliente.
WiFiClient client = server.available();
if (!client) {
return;
}
Serial.println("Nuevo cliente.");
// 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("on12") != -1) {digitalWrite(LED12, HIGH); respuesta="LED 12 encendido";}
else if (req.indexOf("off12") != -1){digitalWrite(LED12, LOW); respuesta="LED 12 apagado";}
else if (req.indexOf("on14") != -1) {digitalWrite(LED14, HIGH); respuesta="LED 14 encendido";}
else if (req.indexOf("off14") != -1){digitalWrite(LED14, LOW); respuesta="LED 14 apagado";}
//////////////////////////////////////////////
// Página WEB. ////////////////////////////
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // Comillas importantes.
client.println(respuesta); // Devuelve respuesta.
client.flush();
client.stop();
Serial.println("Cliente desconectado.");
}
|
- Lo mismo pero en inglés:
AI2_LED_respuesta.ino |
// Juan A. Villalpando.
// KIO4.COM
// Enciende y apaga LED. Botones.
#include <WiFi.h>
const char* ssid = "Nombre_red_WiFi";
const char* password = "contraseña_red";
// 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 LED12 12 // LED12
#define LED14 14 // LED14
String estado = "";
int wait30 = 30000; // time to reconnect when connection is lost.
void setup() {
Serial.begin(115200);
pinMode(LED12, OUTPUT);
pinMode(LED14, OUTPUT);
// 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("on12") != -1) {digitalWrite(LED12, HIGH); estado = "LED12 ON";}
if (req.indexOf("off12") != -1){digitalWrite(LED12, LOW); estado = "LED12 OFF";}
if (req.indexOf("on14") != -1) {digitalWrite(LED14, HIGH); estado = "LED14 ON";}
if (req.indexOf("off14") != -1){digitalWrite(LED14, LOW); estado = "LED14 OFF";}
if (req.indexOf("consulta") != -1){
estado ="";
if (digitalRead(LED12) == HIGH) {estado = "LED12 ON,";} else {estado = "LED12 OFF,";}
if (digitalRead(LED14) == HIGH) {estado = estado + "LED14 ON";} else {estado = estado + "LED14 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.");
}
|
_________________________________
- Propuesta.
- Añade un CampoDeTexto para que el usuario escriba la IP a la que desea conectarse.
_______________________________
|