Tutorial del Internet de las Cosas y Bluetooth con el ESP32
Juan Antonio Villalpando
Volver al índice del tutorial
____________________________
117.- ESP32 y Wifi.
__________________________
0.- Tarjeta D1 R2 ESP32.
- Vamos a utilizar esta tarjeta para trabajar con MQTT.
- Esta tarjeta tiene WIFi, Bluetooth clásico, BLE, ADC, DCA,... y vale unos 5 €.
- Imágenes de esta tarjeta: D1 R2 ESP32
- Comparativa.

- He publicado estos tutoriales en la Comunidad de App Inventor:
https://community.appinventor.mit.edu/t/esp32-wifi-webserver-led-on-off-static-ip-soft-access-point/9323
____________________________________________
1.- Software.
- Utilizarmos esta librería:
https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/ 3
- Disponemos de esta estructura: un Ruter como Punto de Acceso (puede estar conectado a internet o no, ya que vamos a trabajar en red local), tres Estaciones clientes del Ruter.
- Instalaremos un Servidor Web en el ESP32.

________________________________________
2.- Web Server en ESP32 con una página web.
- Se trata de encender/apagar un LED y consultar su estado desde una página web contenida en un Servidor Web instalado en el ESP32.
- El ESP32 es una Estación del Router.
- Instalaremos un Servidor Web en el ESP32, puerto 80.
- Ese Servidor Web dispondrá de una página web.
- Podremos encender/apagar el LED2 (el LED2 es un BUILT-IN LED, es decir está en la placa del ESP32) mediante una página web.
- También podremos consultar el estado del LED2.
Now in a Browser, we write the local IP of the server. We will get a page with three buttons, we can turn on-off and check the status of LED2.
ESP32_servidorweb_pagina.ino |
// Juan A. Villalpando.
// KIO4.COM
// Enciende y apaga LED. Botones.
#include <WiFi.h>
const char* ssid = "Name_WiFi_net";
const char* password = "Password_WiFi_net";
WiFiServer server(80); // Port 80
#define LED2 2 // LED2 is a Built-in LED.
String estado = "";
int wait30 = 30000; // time to reconnect when connection is lost.
void setup() {
Serial.begin(115200);
pinMode(LED2, OUTPUT);
// 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.");
// Esta es la 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("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();
}
|
- Ahora en un navegador web, escribimos la IP local del servidor. Obtendremos una página con tres botones desde donde podremos encender/apagar el LED2 y consultar su estado.

_____________________________
3.- Servidor Web con una IP estática.
- Código similar al anterior. La diferencia es que vamos a configurar el Servidor Web con una IP estática, en mi ejemplo: 192.168.1.115
ESP32_io_estatica.ino |
// Juan A. Villalpando.
// KIO4.COM
// Enciende y apaga LED. Botones.
#include <WiFi.h>
const char* ssid = "Name_WiFi_net";
const char* password = "Password_WiFi_net";
// 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 LED2 2 // LED2 is a Built-in LED.
String estado = "";
int wait30 = 30000; // time to reconnect when connection is lost.
void setup() {
Serial.begin(115200);
pinMode(LED2, 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.");
// Esta es la 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("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();
}
|
____________________________________________________________________________
4.- ESP32 como Punto de Acceso. Servidor Web. Enciende/apaga el LED2. Consulta el estado de LED2.
- Vamos a configurar el ESP32 como Punto de Acceso. El ESP32 creará la red local 192.168.4.X
- A esta red la voy a llamar "juan"
- Esta red es independiente del Ruter.
- Si queremos conectarnos a esta red desde nuestro móvil, debemos cambiar su configuración WiFi [Ajustes / WiFi]
- Esta red se llamará "juan" y tendrá como contraseña: "123456789"
- Si tienes el móvil conectado a tu red WiFi, no funcionará, debes conectarlo a esta nueva red.
 |
 |
ESP32_punto_acceso.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("Setting Access Point: ");
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();
}
|
_______________________________________________________________
5.- App enciende/apaga LED12 y LED14. WiFi. Servidor Web. IP estática.
p125_wemos_led2.aia
- ESP32 es una Estación, un cliente del Ruter.
- IP estática: 192.168.1.115
- Servidor Web , puerto 80.
- Enciende/apaga LED12, LED14.
- Consulta el estado de los LEDs.

_______________________________________
- Bloques.

ESP32_punto_acceso_ipestatica.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.");
}
|
_____________________________________________________________________
6.- App consulta el estado de dos Pulsadores. WiFi. Servidor Web. IP estática.
- ESP32 es una Estación, un cliente del Ruter..
- IP estática: 192.168.1.115
- Servidor Web, puerto: 80.
- Consulta el estado de dos Pulsadores.

_____________________________________________
- Bloques.
ESP32_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.");
}
|
- En vez de poner un Botón podemos poner un Reloj como temporizador.

__________________________________________________________________________
7.- App envía un mensaje al ESP32. Pantalla LCD con I2C. Servidor Web. IP estática.
- ESP32 es una Estación, un cliente del Ruter..
- IP estática: 192.168.1.115
- Servidor Web, puerto: 80.
-
Escribe un mensaje. El mensaje se muestra en la pantalla LCD y en el Monitor Serie.
-
Si el mensaje es: on12, off12, on14, off14 se encenderá/apagará el LED12 o LED14.
-
Consulta el estado de los LEDs.
-
Librería LCD para ESP32:
http://kio4.com/arduino/140_Wemos_LCD.htm
- Buscar imágenes del LCD I2C
_____________________________________
- Bloques.
ESP32_lcd.ino |
// Juan A. Villalpando.
// KIO4.COM
// Enciende y apaga LED. Botones.LCD I2C.
#include
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 LED12 12 // LED12
#define LED14 14 // LED14
String estado = "";
int wait30 = 30000; // time to reconnect when connection is lost.
#include
int columnas = 16;
int filas = 2;
LiquidCrystal_I2C lcd(0x27, columnas, filas);
// LiquidCrystal_I2C lcd(0x3F, columnas, filas);
void setup() {
Serial.begin(115200);
pinMode(LED12, OUTPUT);
pinMode(LED14, OUTPUT);
lcd.init();
lcd.backlight();
// 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 information sends by client.
String req = client.readStringUntil('\r');
Serial.println(req);
req.replace("+", " "); // Para que los espacios no salgan con +
req.replace(" HTTP/1.1", ""); // Para quitar HTTP/1.1
req.replace("GET /", ""); // Para quitar GET /
lcd.clear(); // Clear Screen
lcd.setCursor(0, 0); // Start cursor
lcd.print("Mensaje");
lcd.setCursor(0,1); // Cursor other line.
lcd.print(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.");
}
|
_________________________________________
8.- Ahora todo junto. Propuesta.
- Crea una aplicación:
- Con 4 Botones para encender/apager los LED12 y LED14.
- Una CajaDeTexto para enviar un mensaje y que se muestre en la pantalla LCD I2C.
- Dos Botones para consultar el estado de los LEDs y Pulsadores.

p125wemos_LCD_mensaje_Propuesta.aia (inacabado)
_______________________________________________
9.- Obtener el valor de un potenciómetro. AnalogRead.
p125wemos_Potenciometro.aia
- ESP32 es una Estación, un cliente del Ruter..
- IP estática: 192.168.1.115
- Servidor Web, puerto: 80.
- Podemos obtener el valor de un potenciómetro manualmente mediante un Botón o automáticamente mediante un Reloj con Intervalo = 500

__________________________________________
- Bloques.

Variables:
valor, obtiene valores desde 0 a 4095 (resolución por defecto: 2 ^12)
valor_map, map valor desde 0 a 330
Ent_Anilog, entrada analógica en el termianal 34.
Cuidado: El ESP 32 tiene dos ADC SAR, cuando trabaja con WiFi solo se puede utilizar el SAR ADC1 (GPIOs 32 - 39). Leer esto.
ESP32_potenciometro.ino |
// Juan A. Villalpando.
// http://kio4.com/arduino/212_Wemos_ServoPotenciometro.htm
// Potenciometro.
#include <WiFi.h>
const char* ssid = "Nombre_Red";
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
int wait30 = 30000; // time to reconnect when connection is lost.
const int Ent_Anilogica = 34; // analogic input.
int valor = 0; // valor from 0 to 4095
float valor_map = 0; // map valor from 0 to 330
void setup() {
Serial.begin(115200);
// 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){
valor = analogRead(Ent_Anilogica);
valor_map = map(valor, 0, 4095, 0, 330);
Serial.println(valor);
}
//////////////////////////////////////////////
// Página WEB. ////////////////////////////
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // Comillas importantes.
client.println(valor_map/100); // Return value.
//client.flush();
client.stop();
Serial.println("Client disconnected.");
}
|
_______________________________
|