|     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

____________________________

180.- Wemos D1 R32 ESP32. Bluetooth. App Inventor. Enciende/apaga LED12/LED13. Obtiene el estado de los pulsadores. Envía un mensaje a LCD.

_________________________________________________
18.- Bluetooth. App Inventor. Enciende/apaga LED12/LED13. Obtiene el estado de los pulsadores. Envía un mensaje a LCD.

p62D_esp32_led_pulsa_BT.aia

- Tenemos dos pulsadores, dos LED y una pantalla LCD.

- Disponemos de una aplicación de App Inventor. Cuando pulsamos los Botones 1, 2 3, 4 encendemos/apagamos los LED.

- Cuando pulsamos el Botón5 de "Consultar" nos muestra cómo están los LED y los pulsadores.

- Si escribimos un mensaje en la aplicación, se muestra en la pantalla LCD.

___________________________________________________
- Diseño.

___________________________________________________
- Bloques.

___________________________________________________
- Conexiones.

___________________________________________________
- Código.

led_pulsador.ino

// Juan A. Villalpando.
// KIO4.COM
// Pone los LED12 y LED13 en alto o bajo.
// Consulta el estado de los pulsadores.

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

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth no activado! Activa la conexion Bluetooth.
#endif

BluetoothSerial SerialBT;
 
#define LED12  12    // LED en terminal 12
#define LED13  13    // LED en terminal 12
#define pulsa16 16   // Pulsador en terminal 16.
#define pulsa17 17   // Pulsador en terminal 17.
int valor16;
int valor17;
String d12;
String d13;
String p16;
String p17;
String todos = "0,0,0,0";
String palabra = "-";

void setup() {
  lcd.init();      // Screen LCD                    
  lcd.backlight(); // Screen LCD
  Serial.begin(9600);
  pinMode(LED12, OUTPUT);
  pinMode(LED13, OUTPUT);
  pinMode(pulsa16, INPUT);
  pinMode(pulsa17, INPUT);
  
  SerialBT.begin("ESP32test");
}
 
void loop() {
 if(SerialBT.available()) {
     palabra = SerialBT.readStringUntil('\n');   

     // Realiza la peticion del cliente.
          if (palabra == "on12"){digitalWrite(LED12, HIGH);}
          if (palabra == "off12"){digitalWrite(LED12, LOW);}
          if (palabra == "on13"){digitalWrite(LED13, HIGH);}
          if (palabra == "off13"){digitalWrite(LED13, LOW);}
     
         if (palabra == "consulta"){consulta();}
         if (palabra.indexOf("lcd") != -1)
      {
      palabra = palabra.substring(3,palabra.length());
      escribe_lcd();
       }

} // Fin de available.
} // Fin de loop.

// Consulta el estado de los elementos.
void consulta(){
   if(digitalRead(LED12) == HIGH) {d12 = "LED12 encendido.";} else {d12 = "LED12 apagado.";}
   if(digitalRead(LED13) == HIGH) {d13 = "LED13 encendido.";} else {d13 = "LED13 apagado.";}
 valor16 = digitalRead(pulsa16);
   if (valor16 == HIGH) {p16 = "Pulsador16 PULSADO";} else {p16 = "Pulsador16 NO pulsado";}
 valor17 = digitalRead(pulsa17);
   if (valor17 == HIGH) {p17 = "Pulsador17 PULSADO";} else {p17 = "Pulsador17 NO pulsado";}
  
   todos = d12 + "," + d13 + "," + p16 + "," + p17 + "\n";
   SerialBT.print(todos);
   delay(10);
}

// Pantalla LCD
void escribe_lcd(){
  lcd.clear(); // Borra pantalla.
  lcd.setCursor(0, 0); // Inicio del cursor
  lcd.print(palabra);
  lcd.setCursor(0,1); // Siguiente renglón.
  lcd.print("KIO4.COM");
  Serial.println(palabra);
}

__________________________________________________
2.- Enciende/Apaga el LED4. Callback. Envía un caracter.

p62D_esp32_bluetooth_1.aia

- Este código está realizado para el módulo ESP32 CAM, pero puede funcionar perfectamente con nuestra tarjeta Wemos D1 R32, simplemente cambiando el número del LED. También debes cambiar el nombre del módulo bluetooth.

- Se trata de encender/apagar el LED4 y ver su estado.

- La idea es similar al ejemplo anterior, pero observa el código del ESP, utilizo CallBack, no utilizo el loop().

- La aplicación envía los caracteres 0, 1 y 3.

___________________________________________________
- Diseño.

___________________________________________________
- Bloques.

___________________________________________________
- Código.

- Observa que resta 48, eso es porque, por ejemplo, envía el caracter 1, el ESP recibe el 49, ya que ese es su código ASCII, le restamos 48 y obtenemos el 1.

un_caracter.ino

// Juan A. Villalpando.
// KIO4.COM
// Pone los LED4 en alto o bajo.
// Consulta el estado del LED4.

#include "BluetoothSerial.h"
#define LED4 4

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  initBT();
  pinMode(LED4, OUTPUT);
}

void initBT(){
  if(!SerialBT.begin("ESP32CAM-CLASSIC-BT")){
    Serial.println("An error occurred initializing Bluetooth");
    ESP.restart();
  }else{
    Serial.println("Bluetooth initialized");
  }

  SerialBT.register_callback(btCallback);
  Serial.println("The device started, now you can pair it with bluetooth");
}

void btCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param){
  if(event == ESP_SPP_SRV_OPEN_EVT){
    Serial.println("Client Connected!");
  }else if(event == ESP_SPP_DATA_IND_EVT){
    Serial.printf("ESP_SPP_DATA_IND_EVT len=%d, handle=%d\n\n", param->data_ind.len, param->data_ind.handle);
        String stringRead = String(*param->data_ind.data);
        int paramInt = stringRead.toInt() - 48;
        Serial.printf("paramInt: %d\n", paramInt);
        if(paramInt == 1){digitalWrite(LED4, HIGH); writeSerialBT("LED 4 is ON.");}
        if(paramInt == 0){digitalWrite(LED4, LOW); writeSerialBT("LED 4 is OFF.");}
        if(paramInt == 3){
          if(digitalRead(LED4)){writeSerialBT("LED 4 now is ON.");}
          else {writeSerialBT("LED 4 now is OFF.");}
        }
    }
}

void writeSerialBT(String respuesta){
  SerialBT.println(respuesta);
  SerialBT.flush();
}

void loop() { }

__________________________________________________
3.- Enciende/Apaga el LED4. Callback. Envía un texto.

p62D_esp32_bluetooth_2.aia

- En este ejemplo se envia textos. Si el texto enviado es "Set LED4 ON", "Set LED4 OFF" o "How are you?", se actúa sobre el LED4.

- Si enviamos otro mensaje que no contenga esos textos, nos devolverá el mensaje enviado.

___________________________________________________
- Diseño.

___________________________________________________
- Bloques.

___________________________________________________
- Código.

texto.ino

// Juan A. Villalpando.
// KIO4.COM
// Pone el LED4 en alto o bajo.
// Consulta el estado del LED4.
// Recibe un texto.

#include "BluetoothSerial.h"
#define LED4 4

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  initBT();
  pinMode(LED4, OUTPUT);
}

void initBT(){
  if(!SerialBT.begin("ESP32CAM-CLASSIC-BT")){
    Serial.println("An error occurred initializing Bluetooth");
    ESP.restart();
  }else{
    Serial.println("Bluetooth initialized");
  }

  SerialBT.register_callback(btCallback);
  Serial.println("The device started, now you can pair it with bluetooth");
}

void btCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param){
  if(event == ESP_SPP_SRV_OPEN_EVT){
    Serial.println("Client Connected!");
  }else if(event == ESP_SPP_DATA_IND_EVT){
    Serial.printf("ESP_SPP_DATA_IND_EVT len=%d, handle=%d\n\n", param->data_ind.len, param->data_ind.handle);
        String received = bluetoothReadLine();
        Serial.println(received);
        if(received.indexOf("Set LED4 ON") != -1){digitalWrite(LED4, HIGH); writeSerialBT("LED 4 is ON.");}
        else if(received.indexOf("Set LED4 OFF") != -1){digitalWrite(LED4, LOW); writeSerialBT("LED 4 is OFF.");}
        else if(received.indexOf("How are you?") != -1){
          if(digitalRead(LED4)){writeSerialBT("LED 4 now is ON.");}
          else {writeSerialBT("LED 4 now is OFF.");}
        }
        else {writeSerialBT("Message received: " + received);}
    }
}

String bluetoothReadLine(){
    String text_received = "";
    while(SerialBT.available())
    {
        byte r = SerialBT.read();
        if(r!=13 && r!=10 && char(r)!='\0')
            text_received = text_received + char(r);
    }
    return text_received;      
}


void writeSerialBT(String respuesta){
  SerialBT.println(respuesta);
  SerialBT.flush();
}


void loop() { }

__________________________________________________
4.- Envía tres números y obtiene el doble de cada uno.

p62D_esp32_bluetooth_3.aia

- Escribimos tres números, los enviamos por Bluetooth al ESP32, calcula el doble de cada número y nos lo reenvía.

___________________________________________________
- Diseño.

___________________________________________________
- Bloques.

___________________________________________________
- Código.

tres.ino

// Juan A. Villalpando.
// KIO4.COM
// El doble de tres números.

#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  initBT();
}

void initBT(){
  if(!SerialBT.begin("ESP32CAM-CLASSIC-BT")){
    Serial.println("An error occurred initializing Bluetooth");
    ESP.restart();
  }else{
    Serial.println("Bluetooth initialized");
  }

  SerialBT.register_callback(btCallback);
  Serial.println("The device started, now you can pair it with bluetooth");
}

void btCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param){
  if(event == ESP_SPP_SRV_OPEN_EVT){
    Serial.println("Client Connected!");
  }else if(event == ESP_SPP_DATA_IND_EVT){
        while(SerialBT.available())
             {
              String a =  SerialBT.readStringUntil(',');
              String b =  SerialBT.readStringUntil(',');
              String c =  SerialBT.readStringUntil('\n');
              String retorno = (String)(2 * a.toInt()) +","+ (String)(2 * b.toInt()) +","+ (String)(2 * c.toInt());
              SerialBT.println(retorno);
            } 
    }
}

void loop() { }

__________________________________________________
5.- ESP32 envía continuamente dos números aleatorios a la App y se muestra en una gráfica.

p62D_esp32_bluetooth_5.aia

___________________________________________________
- Diseño.

___________________________________________________
- Bloques.

___________________________________________________
- Código.

cinco.ino

// Juan A. Villalpando.
// http://kio4.com/arduino/180_Wemos_Bluetooth_LED_Pulsadores.htm

#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth no activado! Activa la conexion Bluetooth.
#endif

BluetoothSerial SerialBT;

int alea_1;
int alea_2;
unsigned long tiempo_actual_1 = 0;
unsigned long tiempo_actual_2 = 0;

void setup() {
  Serial.begin(9600);
  SerialBT.begin("ESP32test");
}
 
void loop() {
 if((millis()-tiempo_actual_1)>= 200){
    int alea_1 = random(0,100);
    int alea_2 = random(0,1000);
    tiempo_actual_1 = millis();
    SerialBT.println(String(alea_1) + "," + String(alea_2));
  }
}

 

 

_______________________________

- 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