|     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

____________________________

145.- Wemos D1 R32 ESP32. App Inventor envía mensaje a LCD. LED on/off.

_________________________________
10.-
App Inventor envía mensaje a LCD. LED on/off.

p145wemos_led_LCD.aia

- Escribimos un mensaje en App Inventor y lo enviamos por WiFi para visualizarlo en una pantalla LCD.

- Si escribimos on12, off12, on14, off14 se encenderán/apagarán esos LED.

- En este código no obtenemos respuesta del servidor.

_________________________________
- Diseño.

_________________________________
- Bloques.

_________________________________
- Conexiones.

_________________________________
- Código.

- Vamos a configurarlo con IP estática.

AI2_LED_LCD.ino

// Juan A. Villalpando.
// KIO4.COM
// Envía mensaje
// Desde App Inventor

#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

#include <LiquidCrystal_I2C.h>
int columnas = 16;
int filas = 2;
LiquidCrystal_I2C lcd(0x27, columnas, filas);  
// LiquidCrystal_I2C lcd(0x3F, columnas, filas); 

WiFiServer server(80);
 
void setup() {
  Serial.begin(115200);
  pinMode(LED12, OUTPUT);
  pinMode(LED14, OUTPUT);
  lcd.init();                     
  lcd.backlight();
  
// 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);
  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(); // Borra pantalla.
  lcd.setCursor(0, 0); // Inicio del cursor
  lcd.print("Mensaje");
  lcd.setCursor(0,1); // Siguiente renglón.
  lcd.print(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(""); //  Comillas importantes.

  Serial.print("Cliente desconectado: ");
  Serial.println(client.remoteIP());
  client.flush();
  client.stop();
}

- Es el mismo código pero con comentarios en inglés

AI2_LED_LCD.ino

// Juan A. Villalpando.
// KIO4.COM
// Enciende y apaga LED. Botones.LCD I2C.

#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 LED12  12    // LED12
#define LED14  14    // LED14
String estado = "";
int wait30 = 30000; // time to reconnect when connection is lost.

#include <LiquidCrystal_I2C.h>
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.");
}			
			

 

_________________________________
- Comentarios.

- La información: String req = client.readStringUntil('\r');

llega así: GET /hola+amigo HTTP/1.1

- Reemplazamos GET / y HTTP/1.1 por espacio vacío.

- Quitamos el signo + porque desde Internet el espacio viene así:

hola+amigo

_________________________________
- Propuestas.

- Añade un CampoDeTexto para que el usuario escriba la IP a la que desea conectarse.

- Añade respuesta.

_______________________________

- 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