Tutorial del Internet de las Cosas y Bluetooth con el ESP32
Juan Antonio Villalpando
Volver al índice del tutorial
____________________________
119.- Wemos D1 R32 ESP32. Punto de Acceso. Botón LED.
_________________________________
5.- Crear Punto de Acceso. Encender/apagar un LED mediante un Botón.
- Fíjate que el nombre y contraseña de la red NO es la de nuestro Router, es un nombre y contraseña de la red que queramos crear.
- En mi caso he puesto la red Juan y la contraseña 123456789, puedes poner otra.
- En este caso nuestro dispositivo NO está conectado a nuestro Router ni a Internet.
- Es un Punto de Acceso independiente de nuestro Router.
- Ve al Monitor Serie, en mi caso ha creado la red: 192.168.4.1
- Si en un navegador escribimos esa IP, conectaremos con nuestro Punto de Acceso.
- Pero ATENCIÓN, observa que la red creada es la 192.168.4.X, en cambio la red de nuestro Router es 192.168.1.X
- Son redes distintas, así que en principio desde nuestro ordenador conectado a nuestro Router no podemos entrar en la página 192.168.4.1
- Necesitamos que el ordenador esté en la misma Red WiFi.
- Para probarlo es mejor utilizar nuestro móvil que tiene WiFi.
- Vamos a nuestro móvil. Ajustes. WiFi. Localizamos la Red "Juan", escribimos la contraseña "123456789" y conectamos con el Punto de Acceso que hemos creado.
- Solo permite hasta 4 clientes simultáneos, tal vez se puedan cambiar aquí:
https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/src/WiFiAP.h
- Aquí están las librerías necesarias:
https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFi/src
punto_acceso_BotónLED.ino |
// Juan A. Villalpando.
// KIO4.COM
// Creación de un Punto de Acceso.
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
const char* ssid = "Juan";
const char* password = "123456789";
WiFiServer server(80);
#define LED2 2 // LED en terminal 2
String estado = "";
void setup() {
Serial.begin(115200);
pinMode(LED2, OUTPUT);
// Conecta a la red wifi.
Serial.println();
Serial.print("Configurando Punto de Acceso: ");
Serial.println(ssid);
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
// Esta es la IP
Serial.print("Esta es la IP para conectar: ");
Serial.print("http://");
Serial.println(myIP);
// Inicio del Servidor web.
server.begin();
Serial.println("Servidor web iniciado.");
}
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("on2") != -1) {digitalWrite(LED2, HIGH); estado = "Encendido";}
if (req.indexOf("off2") != -1){digitalWrite(LED2, LOW); estado = "Apagado";}
//////////////////////////////////////////////
// Página WEB. ////////////////////////////
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // Importante.
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head><meta charset=utf-8></head>");
client.println("<body><center><font face='Arial'>");
client.println("<h1>Servidor web con ESP32.</h1>");
client.println("<h2><font color='#009900'>KIO4.COM - Juan A. Villalpando</font></h2>");
client.println("<h3>Página web.</h3>");
client.println("<br><br>");
client.println("<a href='on2'><button>Enciende LED2</button></a>");
client.println("<a href='off2'><button>Apaga LED2</button></a>");
client.println("<br><br>");
client.println(estado);
client.println("</font></center></body></html>");
Serial.print("Cliente desconectado: ");
Serial.println(client.remoteIP());
client.flush();
client.stop();
}
|
______________________________________________________
- Comentarios.
1.- Instala esta aplicación en tu móvil para ver el nivel con el que el Punto de Acceso llega.
2.- Podemos cambiar el canal de transmisión del Punto de Acceso, de esta manera:
WiFi.softAP(ssid, password, 10);
3.- Para ocultar la red podemos poner:
WiFi.softAP(ssid, password, 10, 0);
4.- Red sin clave:
WiFi.softAP(ssid);
5.- Mediante esta orden podemos ver el número de dispositivos conectados a nuestro Punto de Acceso, el máximo es 5.
WiFi.softAPgetStationNum()
6.- Desconectar un cliente.
WiFi.softAPdisconnect();
- Canal muy saturado. Analizador de WiFi.
- Instalamos en nuestro móvil esta aplicación de la Play Store de Google:
WiFi Analyzer
- Observamos los WiFi que hay en nuestra proximidad.
- Puede ocurrir que en el mismo canal "convivan" muchos WiFi, en este caso sería conveniente cambiar el canal de nuestro WiFi mediante la orden que acabamos de ver: WiFi.softAP(ssid, password, 10);
- Si en el mismo canal "conviven" muchos WiFi será un canal saturado y la red se enlentecerá, incluso se bloqueará. |
|
_________________________________
- Propuestas.
1.- Establece que el Punto de acceso tenga cierta IP.
2.- Crea un tercer Botón llamado "Ver estado", que cuando lo pulses obtenga el estado del LED sin modificarlo.
3.- Conecta otro LED en otro terminal.
-----------------
- IP estática:
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password);
Serial.println("Wait 100 ms for AP_START...");
delay(100);
Serial.println("Set softAPConfig");
IPAddress Ip(192, 168, 1, 1);
IPAddress NMask(255, 255, 255, 0);
WiFi.softAPConfig(Ip, Ip, NMask);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
______________________________________________________
- Cambiar la IP:
https://github.com/esp8266/Arduino/issues/2208
- En el siguiente código el Wemos está conectado al Router y además es un Punto de Acceso. El móvil está conectado también al Router, pero para el funcionamiento del encendido/apagado, ponemos la IP del Wemos.
https://randomnerdtutorials.com/esp32-access-point-ap-web-server/
punto_acceso_BotónLED.ino |
// Juan A. Villalpando.
// KIO4.COM
// Creación de un Punto de Acceso.
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
const char* ssid = "Juan";
const char* password = "123456789";
WiFiServer server(80); // Port 80
#define LED2 2 // LED2 is a Built-in LED.
String estado = "";
void setup() {
Serial.begin(115200);
pinMode(LED2, OUTPUT);
// Conecta a la red wifi.
Serial.println();
Serial.print("Configurando Punto de Acceso: ");
Serial.println(ssid);
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
// Esta es la IP
Serial.print("This is IP to connect to the WebServer: ");
Serial.print("http://");
Serial.println(myIP);
// Start Web Server.
server.begin();
Serial.println("Web Server started.");
}
void loop() {
// 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("on2") != -1) {digitalWrite(LED2, HIGH); estado = "ON";}
if (req.indexOf("off2") != -1){digitalWrite(LED2, LOW); estado = "OFF";}
if (req.indexOf("consulta") != -1){
if (digitalRead(LED2)){estado = "LED2 now is ON";}
else {estado = "LED2 now is OFF";}
}
//////////////////////////////////////////////
// WEB PAGE. ////////////////////////////
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // Important.
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head><meta charset=utf-8></head>");
client.println("<body><center><font face='Arial'>");
client.println("<h1>Servidor web con ESP32.</h1>");
client.println("<h2><font color='#009900'>KIO4.COM - Juan A. Villalpando</font></h2>");
client.println("<h3>Página web.</h3>");
client.println("<br><br>");
client.println("<a href='on2'><button>Click to ON LED2</button></a>");
client.println("<a href='off2'><button>Click to OFF LED2</button></a>");
client.println("<a href='consulta'><button>Consult status LED2</button></a>");
client.println("<br><br>");
client.println(estado);
client.println("</font></center></body></html>");
Serial.print("Client disconnected: ");
Serial.println(client.remoteIP());
client.flush();
client.stop();
}
|
_______________________________
|