<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bluetooth Archives &#8226; HUE CAT INGENIERÍA ESPAÑA</title>
	<atom:link href="https://huecat.es/tag/bluetooth/feed/" rel="self" type="application/rss+xml" />
	<link>https://huecat.es/tag/bluetooth/</link>
	<description>Diseño, Programación y Electrónica</description>
	<lastBuildDate>Sun, 06 Jul 2025 19:47:15 +0000</lastBuildDate>
	<language>es</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://huecat.es/wp-content/uploads/2020/10/cropped-huecat-logo-1-1-512-32x32.png</url>
	<title>Bluetooth Archives &#8226; HUE CAT INGENIERÍA ESPAÑA</title>
	<link>https://huecat.es/tag/bluetooth/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Controlar un ESP32 (o esp8266) con Android utilizando AppInventor2</title>
		<link>https://huecat.es/controlar-un-esp32-o-esp8266-con-android-utilizando-appinventor/</link>
					<comments>https://huecat.es/controlar-un-esp32-o-esp8266-con-android-utilizando-appinventor/#respond</comments>
		
		<dc:creator><![CDATA[HUECAT]]></dc:creator>
		<pubDate>Mon, 27 Nov 2023 18:01:02 +0000</pubDate>
				<category><![CDATA[ESP32]]></category>
		<category><![CDATA[ESP8266]]></category>
		<category><![CDATA[Arduino IDE]]></category>
		<category><![CDATA[Ble]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[IDE]]></category>
		<guid isPermaLink="false">https://huecat.es/?p=6976</guid>

					<description><![CDATA[<p>App Inventor 2 es una plataforma en línea de código abierto que permite crear aplicaciones para dispositivos Android sin necesidad de conocimientos avanzados de programación. F App Inventor 2 fue desarrollado por Google y posteriormente transferido al MIT (Instituto Tecnológico de Massachusetts). Para este proyecto se creará una aplicación en App Inventor que se conecte [&#8230;]</p>
<p>The post <a href="https://huecat.es/controlar-un-esp32-o-esp8266-con-android-utilizando-appinventor/">Controlar un ESP32 (o esp8266) con Android utilizando AppInventor2</a> appeared first on <a href="https://huecat.es">HUE CAT INGENIERÍA ESPAÑA</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>App Inventor 2 es una plataforma en línea de código abierto que permite crear aplicaciones para dispositivos Android sin necesidad de conocimientos avanzados de programación. F</p>



<p>App Inventor 2 fue desarrollado por Google y posteriormente transferido al MIT (Instituto Tecnológico de Massachusetts).</p>



<p><strong>Para este proyecto se creará  una aplicación en App Inventor que se conecte a un slider a través de Bluetooth y lo controle desde un dispositivo programado con Arduino IDE</strong></p>



<p></p>



<p></p>



<p>Aplicación en App Inventor que se conecte a un slider a través de Bluetooth y se controle desde un dispositivo Arduino con un ESP32, puedes seguir estos pasos generales:</p>



<p></p>



<h2 class="wp-block-heading">Lado de la Aplicación en App Inventor:</h2>



<p>1. <strong>Crear la Interfaz Gráfica:</strong></p>



<figure class="wp-block-image size-large"><a href="https://huecat.es/wp-content/uploads/2023/11/2023-12-05-00_25_31-MIT-App-Inventor-—-Mozilla-Firefox.png"><img fetchpriority="high" decoding="async" width="1024" height="718" src="https://huecat.es/wp-content/uploads/2023/11/2023-12-05-00_25_31-MIT-App-Inventor-—-Mozilla-Firefox-1024x718.png" alt="" class="wp-image-7010" srcset="https://huecat.es/wp-content/uploads/2023/11/2023-12-05-00_25_31-MIT-App-Inventor-—-Mozilla-Firefox-1024x718.png 1024w, https://huecat.es/wp-content/uploads/2023/11/2023-12-05-00_25_31-MIT-App-Inventor-—-Mozilla-Firefox-300x210.png 300w, https://huecat.es/wp-content/uploads/2023/11/2023-12-05-00_25_31-MIT-App-Inventor-—-Mozilla-Firefox-768x539.png 768w, https://huecat.es/wp-content/uploads/2023/11/2023-12-05-00_25_31-MIT-App-Inventor-—-Mozilla-Firefox.png 1232w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p><strong>2. Comienza un nuevo proyecto</strong></p>



<figure class="wp-block-image size-large"><a href="https://huecat.es/wp-content/uploads/2023/11/2023-11-27-22_52_29-MIT-App-Inventor-—-Mozilla-Firefox.png"><img decoding="async" width="1024" height="497" src="https://huecat.es/wp-content/uploads/2023/11/2023-11-27-22_52_29-MIT-App-Inventor-—-Mozilla-Firefox-1024x497.png" alt="" class="wp-image-7002" srcset="https://huecat.es/wp-content/uploads/2023/11/2023-11-27-22_52_29-MIT-App-Inventor-—-Mozilla-Firefox-1024x497.png 1024w, https://huecat.es/wp-content/uploads/2023/11/2023-11-27-22_52_29-MIT-App-Inventor-—-Mozilla-Firefox-300x146.png 300w, https://huecat.es/wp-content/uploads/2023/11/2023-11-27-22_52_29-MIT-App-Inventor-—-Mozilla-Firefox-768x373.png 768w, https://huecat.es/wp-content/uploads/2023/11/2023-11-27-22_52_29-MIT-App-Inventor-—-Mozilla-Firefox-1536x746.png 1536w, https://huecat.es/wp-content/uploads/2023/11/2023-11-27-22_52_29-MIT-App-Inventor-—-Mozilla-Firefox.png 1896w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p>3. <strong>Componentes Bluetooth:</strong> Añadir el componente Bluetooth al diseño.</p>



<p></p>



<p></p>



<p></p>



<p>4. <strong>Configurar Bluetooth:</strong></p>



<ul class="wp-block-list">
<li>Configurar el componente Bluetooth para buscar dispositivos y establecer la conexión.</li>
</ul>



<ol class="wp-block-list">
<li><strong>Programar la Interacción con el Slider:</strong>
<ul class="wp-block-list">
<li>Programar la lógica que enviará los datos del slider a través de Bluetooth al dispositivo Arduino cuando se modifique su valor.</li>
</ul>
</li>



<li><strong>Manejar la Conexión y Desconexión:</strong>
<ul class="wp-block-list">
<li>Implementar lógica para gestionar la conexión y desconexión con el dispositivo Bluetooth.</li>
</ul>
</li>



<li><strong>Diseñar la Interfaz de Usuario:</strong>
<ul class="wp-block-list">
<li>Diseñar la interfaz de usuario para mostrar el estado de la conexión y otra información relevante.</li>
</ul>
</li>
</ol>



<p>En la pantalla de diseño, agrega un componente <code>Slider</code> desde la paleta de componentes.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">


Manejo del Slider y envío de datos:

En el bloque &quot;BluetoothClient1.SendText&quot;, el valor del slider se convierte a una cadena (Text), ya que el módulo Bluetooth envía datos como texto.

Asegúrate de configurar correctamente el BluetoothClient1.Address con la dirección Bluetooth de tu dispositivo.

Conecta tu dispositivo Android a tu Arduino mediante Bluetooth.
</pre></div>


<p></p>



<p></p>



<h2 class="wp-block-heading">Lado del Dispositivo Arduino (ESP32):</h2>



<ol class="wp-block-list">
<li><strong>Preparar todo para poder configurar el ESP32 con Arduino IDE.</strong>
<ul class="wp-block-list">
<li>Si aún no has configurado el Arduino IDE para tu ESP32, <a href="https://huecat.es/arduino-ide-compilar-codigo-para-esp32-esp8266/">puedes seguir estos pasos: Configurar el ESP32 con Arduino IDE</a></li>
</ul>
</li>



<li><strong>Programar la Lógica del Arduino</strong> <strong>Controlar el Slider</strong> (recibir datos)






<ul class="wp-block-list">
<li>Escribe un programa para el ESP32 que escuche los datos enviados por la aplicación a través de Bluetooth.</li>
</ul>



<ul class="wp-block-list">
<li>Implementa la lógica que ajustará el valor del slider según los datos recibidos a través de Bluetooth.</li>
</ul>
</li>
</ol>



<p></p>



<p></p>



<p>Controlar un slider en App Inventor 2 y enviar los datos al ESP32 a través de Bluetooth</p>



<p> Asegurarse tener un módulo Bluetooth conectado al microcontrolador.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: cpp; title: ; notranslate">
// Importar la librería para el módulo Bluetooth
#include &lt;SoftwareSerial.h&gt;

SoftwareSerial BTSerial(10, 11); // RX, TX

void setup() {
  Serial.begin(9600);
  BTSerial.begin(9600);
}

void loop() {
  if (BTSerial.available()) {
    int valor = BTSerial.parseInt();
    if (valor &gt;= 0 &amp;&amp; valor &lt;= 255) {
      // Aquí puedes utilizar el valor recibido como desees
      analogWrite(9, valor); // Por ejemplo, controlar un LED con el valor del slider
    }
  }
}
</pre></div>


<p></p>



<p></p>



<p>Este código utiliza la librería <code>SoftwareSerial</code> para comunicarse con el módulo Bluetooth en los pines 10 y 11. Luego, lee el valor entero enviado desde la aplicación y lo utiliza para controlar un LED conectado al pin 9 (se puede ajustar esto según tu configuración).</p>
<p>The post <a href="https://huecat.es/controlar-un-esp32-o-esp8266-con-android-utilizando-appinventor/">Controlar un ESP32 (o esp8266) con Android utilizando AppInventor2</a> appeared first on <a href="https://huecat.es">HUE CAT INGENIERÍA ESPAÑA</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://huecat.es/controlar-un-esp32-o-esp8266-con-android-utilizando-appinventor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Conectar dos placas ESP32 con Bluetooth</title>
		<link>https://huecat.es/conectar-dos-placas-esp32-con-bluetooth/</link>
					<comments>https://huecat.es/conectar-dos-placas-esp32-con-bluetooth/#comments</comments>
		
		<dc:creator><![CDATA[HUECAT]]></dc:creator>
		<pubDate>Mon, 14 Mar 2022 21:18:00 +0000</pubDate>
				<category><![CDATA[ESP32]]></category>
		<category><![CDATA[STEM]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<guid isPermaLink="false">https://huecat.es/?p=6377</guid>

					<description><![CDATA[<p>Creado:: 22 de marzo de 2023 Ultima actualización: 7/5/2025 Primeros pasos con ESP32 Bluetooth Low Energy (BLE) en Arduino IDE &#8211; Bluetooth de Bajo Consumo de Energía El ESP32 cuenta con con Bluetooth Clásico y Bluetooth Low Energy (BLE) Esta publicación es una introducción a BLE con el ESP32. En esta sección: ¿Qué es BLE [&#8230;]</p>
<p>The post <a href="https://huecat.es/conectar-dos-placas-esp32-con-bluetooth/">Conectar dos placas ESP32 con Bluetooth</a> appeared first on <a href="https://huecat.es">HUE CAT INGENIERÍA ESPAÑA</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://huecat.es/wp-content/uploads/2022/03/esp32_bluetooth.png"><img decoding="async" width="1024" height="683" src="https://huecat.es/wp-content/uploads/2022/03/esp32_bluetooth-1024x683.png" alt="" class="wp-image-7332" srcset="https://huecat.es/wp-content/uploads/2022/03/esp32_bluetooth-1024x683.png 1024w, https://huecat.es/wp-content/uploads/2022/03/esp32_bluetooth-300x200.png 300w, https://huecat.es/wp-content/uploads/2022/03/esp32_bluetooth-768x512.png 768w, https://huecat.es/wp-content/uploads/2022/03/esp32_bluetooth-1500x1000.png 1500w, https://huecat.es/wp-content/uploads/2022/03/esp32_bluetooth.png 1536w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p><a href="Actualizado: 22 de marzo de 2023">Creado:: 22 de marzo de 2023</a></p>



<p><a href="Actualizado: 22 de marzo de 2023">Ultima actualización: 7/5/2025</a></p>



<h2 class="wp-block-heading">Primeros pasos con ESP32 Bluetooth Low Energy (BLE) en Arduino IDE &#8211; Bluetooth de Bajo Consumo de Energía</h2>



<figure class="wp-block-image size-large"><a href="https://huecat.es/wp-content/uploads/2023/03/BluetoothLogo.svg.png"><img decoding="async" width="1024" height="251" src="https://huecat.es/wp-content/uploads/2023/03/BluetoothLogo.svg-1024x251.png" alt="" class="wp-image-6381" srcset="https://huecat.es/wp-content/uploads/2023/03/BluetoothLogo.svg-1024x251.png 1024w, https://huecat.es/wp-content/uploads/2023/03/BluetoothLogo.svg-300x73.png 300w, https://huecat.es/wp-content/uploads/2023/03/BluetoothLogo.svg-768x188.png 768w, https://huecat.es/wp-content/uploads/2023/03/BluetoothLogo.svg-1536x376.png 1536w, https://huecat.es/wp-content/uploads/2023/03/BluetoothLogo.svg.png 1920w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p>El ESP32 cuenta con con Bluetooth Clásico y Bluetooth Low Energy (BLE)</p>



<p>Esta publicación es una introducción a BLE con el ESP32. </p>



<pre class="wp-block-preformatted">En esta sección: ¿Qué es BLE y para qué se puede usar?</pre>



<p>También algunos ejemplos con el ESP32 usando Arduino IDE. </p>



<p></p>



<p></p>



<h2 class="wp-block-heading">¿Qué es Bluetooth de baja energía?</h2>



<p><br>Bluetooth Low Energy, BLE para abreviar, es una variante de ahorro de energía de Bluetooth. La aplicación principal de BLE es la transmisión a corta distancia de pequeñas cantidades de datos (bajo ancho de banda).</p>



<p> A diferencia de Bluetooth Clásico, que siempre está activado, BLE permanece en modo de suspensión constantemente, excepto cuando se inicia una conexión.</p>



<p>Comparado con Bluetooth clásico, Bluetooth Low Energy está diseñado para proporcionar un bajo consumo de energía, manteniendo un rango de alcance de comunicación similar.</p>



<p>Esto hace que consuma muy poca energía. BLE consume aproximadamente 100 veces menos energía que Bluetooth (según el caso de uso).</p>



<p></p>



<p>Además, BLE admite no solo la comunicación punto a punto, sino también el modo de transmisión y la red de malla.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading">Servidor y cliente BLE</h2>



<p>Con Bluetooth Low Energy, hay dos tipos de dispositivos: el servidor y el cliente.</p>



<p>El ESP32 puede actuar como cliente o como servidor. El servidor anuncia su existencia, por lo que otros dispositivos pueden encontrarlo y contiene datos que el cliente puede leer. El cliente escanea los dispositivos cercanos y, cuando encuentra el servidor que está buscando, establece una conexión y escucha los datos entrantes. Esto se llama comunicación punto a punto.</p>



<p>Hay otros modos de comunicación posibles, como el modo de transmisión y la red de malla.</p>



<p></p>



<h2 class="wp-block-heading">GATT</h2>



<p>GATT significa Atributos Genéricos y define una estructura de datos jerárquica que está expuesta a los dispositivos BLE conectados. Esto significa que GATT define la forma en que dos dispositivos BLE envían y reciben mensajes estándar. Comprender esta jerarquía es importante porque facilitará la comprensión de cómo usar BLE con el ESP32.</p>



<figure class="wp-block-image size-full"><a href="https://huecat.es/wp-content/uploads/2023/03/GATT-ESP32-BLE-Server-Client-Example.webp"><img decoding="async" width="750" height="423" src="https://huecat.es/wp-content/uploads/2023/03/GATT-ESP32-BLE-Server-Client-Example.webp" alt="" class="wp-image-6392" srcset="https://huecat.es/wp-content/uploads/2023/03/GATT-ESP32-BLE-Server-Client-Example.webp 750w, https://huecat.es/wp-content/uploads/2023/03/GATT-ESP32-BLE-Server-Client-Example-300x169.webp 300w" sizes="(max-width: 750px) 100vw, 750px" /></a></figure>



<p><strong>Perfil</strong>: colección estándar de servicios para un caso de uso específico;</p>



<p><strong>Servicio</strong>: recopilación de información relacionada, como lecturas de sensores, nivel de batería, frecuencia cardíaca, etc.;</p>



<p><strong>Característica</strong>: es donde se guardan los datos reales en la jerarquía (valor); </p>



<p><strong>Descriptor</strong>: metadatos sobre los datos; </p>



<p>Propiedades: describe cómo se puede interactuar con el valor característico. Por ejemplo: leer, escribir, notificar, difundir, indicar, etc.</p>



<p>En nuestro ejemplo, crearemos un servicio con dos características.</p>



<p>Uno para la temperatura y otro para la humedad.</p>



<p>Las lecturas reales de temperatura y humedad se guardan en el valor bajo sus características. Cada característica tiene la propiedad de notificación, de modo que notifique al cliente cada vez que cambien los valores.</p>



<p></p>



<p><strong>UUI</strong></p>



<p><strong>Cada servicio, característica y descriptor tiene un UUID (Universally Unique Identifier). Un UUID es un número único de 128 bits (16 bytes).</strong></p>



<p><strong> Por ejemplo: </strong></p>



<p><strong>55072829-bc9e-4c53-938a-74a6d4c78776</strong></p>



<p><strong>Hay UUID abreviados para todos los tipos, servicios y perfiles especificados en el SIG (Bluetooth Special Interest Group).</strong></p>



<p>S<strong>i su aplicación necesita su propio UUID, puede generarlo utilizando este sitio web generador de UUID. </strong></p>



<p><strong>En resumen, el UUID se utiliza para identificar información de manera única. Por ejemplo, puede identificar un servicio particular proporcionado por un dispositivo Bluetooth.</strong></p>



<p></p>



<h2 class="wp-block-heading">Conectando el ESP32</h2>



<p>Este ejemplo funcionaría para cualquier placa de desarrollo actual con ESP-32. En este caco se utilizaron las siguientes placas:</p>



<figure class="wp-block-image size-large"><a href="https://huecat.es/wp-content/uploads/2023/03/ESP32-scaled.jpg"><img decoding="async" width="1024" height="769" src="https://huecat.es/wp-content/uploads/2023/03/ESP32-1024x769.jpg" alt="" class="wp-image-6413" srcset="https://huecat.es/wp-content/uploads/2023/03/ESP32-1024x769.jpg 1024w, https://huecat.es/wp-content/uploads/2023/03/ESP32-300x225.jpg 300w, https://huecat.es/wp-content/uploads/2023/03/ESP32-768x577.jpg 768w, https://huecat.es/wp-content/uploads/2023/03/ESP32-1536x1153.jpg 1536w, https://huecat.es/wp-content/uploads/2023/03/ESP32-2048x1538.jpg 2048w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption class="wp-element-caption">Heltec ESP32 Lora V2, LolinD32, NodeMCU ESP32S</figcaption></figure>



<p></p>



<h3 class="wp-block-heading">Sketch para Servidor BLE</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: cpp; title: ; notranslate">
#define LED_BUILTIN 2
#include &lt;BLEDevice.h&gt;
#include &lt;BLEServer.h&gt;
#include &lt;BLEUtils.h&gt;
#include &lt;BLE2902.h&gt;

#define temperatureCelsius
#define BLE_server &quot;ESP32_Server&quot;

#define SERVICE_UUID &quot;huecat23-6d3c-4a17-a71f-ece2e6075f9b&quot;

BLECharacteristic dhtTemperatureCelsiusCharacteristics(&quot;huecat23-c85e-4596-9bd9-015e2eaa4888&quot;, BLECharacteristic::PROPERTY_NOTIFY);
BLEDescriptor dhtTemperatureCelsiusDescriptor(BLEUUID((uint16_t)0x2902));

BLECharacteristic dhtHumidityCharacteristics(&quot;huecat23-4a2f-4cf3-96e6-38b79be71a61&quot;, BLECharacteristic::PROPERTY_NOTIFY);
BLEDescriptor dhtHumidityDescriptor(BLEUUID((uint16_t)0x2903));


bool device_connected = false;

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      device_connected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      device_connected = false;
    }
};

void setup() {

  Serial.begin(115200);

  BLEDevice::init(BLE_server);
  BLEServer *pServer = BLEDevice::createServer();
  pServer-&gt;setCallbacks(new MyServerCallbacks());
  BLEService *dhtService = pServer-&gt;createService(SERVICE_UUID);


  dhtService-&gt;addCharacteristic(&amp;dhtTemperatureCelsiusCharacteristics);
  dhtTemperatureCelsiusDescriptor.setValue(&quot;DHT Temperature (Celsius)&quot;);
  dhtTemperatureCelsiusCharacteristics.addDescriptor(new BLE2902());

  dhtService-&gt;addCharacteristic(&amp;dhtHumidityCharacteristics);
  dhtHumidityDescriptor.setValue(&quot;DHT humidity&quot;);
  dhtHumidityCharacteristics.addDescriptor(new BLE2902());
  dhtService-&gt;start();
  pServer-&gt;getAdvertising()-&gt;start();
  Serial.println(&quot;Esperando a Cliente Bluetooth&quot;);
}
void loop() {


  //Timer cada 5 segundos: envía la info por bluetooth
  static unsigned long enviaDato;
  if (millis() &gt; enviaDato + 5000) {
    enviaDato = millis();

    ///////////////////////////////// 
      if (device_connected) {

    //Datos de prueba
    float temp = 25;
    float hum = 88;
    
    static char temperature_celsius&#x5B;7];
    dtostrf(temp, 6, 2, temperature_celsius);
    dhtTemperatureCelsiusCharacteristics.setValue(temperature_celsius);
    dhtTemperatureCelsiusCharacteristics.notify();
    Serial.print(&quot;Temperatura: &quot;);
    Serial.print(temp);
    Serial.print(&quot; *C&quot;);

    static char humidity&#x5B;7];
    dtostrf(hum, 6, 2, humidity);
    dhtHumidityCharacteristics.setValue(humidity);
    dhtHumidityCharacteristics.notify();
    Serial.print(&quot;  Humedad: &quot;);
    Serial.print(hum);
    Serial.println(&quot; %&quot;);
  }



    
  }

  

  //Parpadeo del LED
  static unsigned long parpadeo;
  if (millis() &gt; parpadeo + 80) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    parpadeo = millis();
  }

}
</pre></div>


<p></p>



<h3 class="wp-block-heading">Sketch para el Cliente  BLE</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: cpp; title: ; notranslate">
#include &quot;BLEDevice.h&quot;
#include &quot;heltec.h&quot;
#include &quot;Arduino.h&quot;


SSD1306Wire display(0x3c, SDA_OLED, SCL_OLED, RST_OLED); //128_64

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

#define temperatureCelsius
#define BLE_server &quot;ESP32_Server&quot;


// Generador de UUIDs:
// https://www.uuidgenerator.net/

//***********************************
//BLE ID UNICO PARA SERVICIO
static BLEUUID                dhtServiceUUID(&quot;huecat23-6d3c-4a17-a71f-ece2e6075f9b&quot;);
//***********************************

//BLE ID UNICO PARA CARACTERÍSTICA (TEMPERATURA)
static BLEUUID temperatureCharacteristicUUID(&quot;huecat23-c85e-4596-9bd9-015e2eaa4888&quot;);

//BLE ID UNICO PARA CARACTERÍSTICA (HUMEDAD)
static BLEUUID    humidityCharacteristicUUID(&quot;huecat23-4a2f-4cf3-96e6-38b79be71a61&quot;);


/*

  //***********************************
  //BLE ID UNICO PARA SERVICIO
  static BLEUUID dhtServiceUUID(&quot;d29181ad-6d3c-4a17-a71f-ece2e6075f9b&quot;);
  //***********************************

  //BLE ID UNICO PARA CARACTERÍSTICA (TEMPERATURA)
  static BLEUUID temperatureCharacteristicUUID(&quot;ea4963df-c85e-4596-9bd9-015e2eaa4888&quot;);

  //BLE ID UNICO PARA CARACTERÍSTICA (HUMEDAD)
  static BLEUUID humidityCharacteristicUUID(&quot;b61decbb-4a2f-4cf3-96e6-38b79be71a61&quot;);


*/
static boolean bleConectado = false;
static boolean connected = false;

static BLEAddress *pServerAddress;
static BLERemoteCharacteristic* temperatureCharacteristic;
static BLERemoteCharacteristic* humidityCharacteristic;

const uint8_t notificationOn&#x5B;] = {0x1, 0x0};
const uint8_t notificationOff&#x5B;] = {0x0, 0x0};


bool conectarAServidor(BLEAddress pAddress) {
  BLEClient* pClient = BLEDevice::createClient();

  pClient-&gt;connect(pAddress);
  Serial.println(&quot;Conectado al Servidor&quot;);

  BLERemoteService* pRemoteService = pClient-&gt;getService(dhtServiceUUID);

  if (pRemoteService == nullptr) {
    Serial.print(&quot;Failed to find our service UUID: &quot;);
    Serial.println(dhtServiceUUID.toString().c_str());
    return (false);
  }

  temperatureCharacteristic = pRemoteService-&gt;getCharacteristic(temperatureCharacteristicUUID);
  humidityCharacteristic = pRemoteService-&gt;getCharacteristic(humidityCharacteristicUUID);

  if (temperatureCharacteristic == nullptr || humidityCharacteristic == nullptr) {
    Serial.print(&quot;Failed to find our characteristic UUID&quot;);
    return false;
  }
  Serial.println(&quot; Characteristics Found!&quot;);

  temperatureCharacteristic-&gt;registerForNotify(temperatureNotifyCallback);
  humidityCharacteristic-&gt;registerForNotify(humidityNotifyCallback);
}

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      if (advertisedDevice.getName() == BLE_server) {
        advertisedDevice.getScan()-&gt;stop();
        pServerAddress = new BLEAddress(advertisedDevice.getAddress());
        bleConectado = true;
        Serial.println(&quot;Dispositivo encontrado. Conectando...&quot;);
      }
    }
};

static void temperatureNotifyCallback(BLERemoteCharacteristic*pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify)
{

  String informarTemperatura = &quot;&quot;;
  informarTemperatura = &quot;Temperatura: &quot;;
  informarTemperatura += (char*)pData;
  informarTemperatura += &quot; *C&quot;;

  imprimirConAltura(informarTemperatura, 20); ////// IMPRIME OLED Y SERIAL //////

}

static void humidityNotifyCallback(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify) {

  String informarHumedad = &quot;Humedad: &quot;;
  informarHumedad += (char*)pData;
  informarHumedad += &quot; %&quot;;

  //imprimirConAltura(informarHumedad, 28); ////// IMPRIME OLED Y SERIAL //////

  Serial.println(informarHumedad);
}

void setup()
{
  Serial.begin(115200);
  Serial.println(&quot;\nESP-32--B-BLE-CLIENTE&quot;);

  ///////////////////////////////////////// PARA PANTALLA OLED
  initHeltecEsp32(); //Inicializaciones correspondientes a modelo Pantalla OLED elegido.

  imprimirConAltura(&quot;Comenzando conexión BLE ( Cliente)&quot;, 0); ////// IMPRIME OLED Y SERIAL //////

  BLEDevice::init(&quot;&quot;);

  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan-&gt;setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan-&gt;setActiveScan(true);
  pBLEScan-&gt;start(30);


}
void loop() {

  if (bleConectado == true) {

    if (conectarAServidor(*pServerAddress)) {

      String conectando = &quot;Conectado servidor BLE.&quot;;
      imprimirConAltura(conectando, 8); ////// IMPRIME OLED Y SERIAL //////

      temperatureCharacteristic-&gt;getDescriptor(BLEUUID((uint16_t)0x2902))-&gt;writeValue((uint8_t*)notificationOn, 2, true);
      humidityCharacteristic-&gt;getDescriptor(BLEUUID((uint16_t)0x2902))-&gt;writeValue((uint8_t*)notificationOn, 2, true);
      connected = true;
    } else {
      String conectando_error = &quot;Falló conexión Servidor BLE&quot;;
      imprimirConAltura(conectando_error, 8); ////// IMPRIME OLED Y SERIAL //////
    }
    bleConectado = false;
  }
  delay(1000);
}



//Basado en ejemplo Heltec OLED_rotate.ino
void VextON(void)
{
  pinMode(Vext, OUTPUT);
  digitalWrite(Vext, LOW);
}

void VextOFF(void) //Vext default OFF
{
  pinMode(Vext, OUTPUT);
  digitalWrite(Vext, HIGH);
}

void initHeltecEsp32() {

  VextON();
  delay(100);

  display.init();
  display.clear();
  display.display();

  display.setContrast(1);

  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.clear();
  display.display();
  display.screenRotate(ANGLE_0_DEGREE);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 32 - 16 / 2, &quot;HUE CAT&quot;); //ROTATE_0
  display.display();
  delay(400);

  display.clear();
  display.display();
  display.screenRotate(ANGLE_90_DEGREE);
  display.setFont(ArialMT_Plain_10);
  display.drawString(32, 64 - 10 / 2, &quot;HUE CAT&quot;); //ROTATE_90
  display.display();
  delay(400);

  display.clear();
  display.display();
  display.screenRotate(ANGLE_180_DEGREE);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 32 - 16 / 2, &quot;HUE CAT&quot;); //ROTATE_180
  display.display();
  delay(400);

  display.clear();
  display.display();
  display.screenRotate(ANGLE_270_DEGREE);
  display.setFont(ArialMT_Plain_10);
  display.drawString(32, 64 - 10 / 2, &quot;HUE CAT&quot;); //ROTATE_270
  display.display();
  delay(400);

  display.clear();
  display.display();
  display.screenRotate(ANGLE_0_DEGREE);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 32 - 16 / 2, &quot;HUE CAT&quot;); //ROTATE_0
  display.display();
  delay(500);

  display.clear();
  display.display();

  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.setFont(ArialMT_Plain_10);

}


void imprimirConAltura(String stringToPrint, int alturaAImprimir) {
  //Imprime en monitor serie y display
  Serial.print(&quot;OLED-&gt;&quot; + stringToPrint);
  display.drawString(0, alturaAImprimir, stringToPrint);
  display.display();
}
</pre></div>


<p></p>
<p>The post <a href="https://huecat.es/conectar-dos-placas-esp32-con-bluetooth/">Conectar dos placas ESP32 con Bluetooth</a> appeared first on <a href="https://huecat.es">HUE CAT INGENIERÍA ESPAÑA</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://huecat.es/conectar-dos-placas-esp32-con-bluetooth/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
	</channel>
</rss>
