Advertisement
Danixu

Bluetooth Reconnect

Jun 14th, 2021
1,825
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. /*
  2.   Program to control LED (ON/OFF) from ESP32 using Serial Bluetooth
  3.   by Daniel Carrasco -> https://www.electrosoftcloud.com/
  4. */
  5. #include "BluetoothSerial.h"
  6. #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
  7. #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
  8. #endif
  9.  
  10. BluetoothSerial BT; // Objeto Bluetooth
  11. String clientName = "ESP32_LED_Control";
  12. bool connected;
  13. TaskHandle_t ConnectBluetoothHandle;
  14.  
  15. // Function prototype
  16. void callback_function(esp_spp_cb_event_t event, esp_spp_cb_param_t *param);
  17.  
  18. void ConnectBluetooth(void *pvParameters) {
  19.   // connect to bluetooth.
  20.   for (;;) { // A Task shall never return or exit.
  21.     connected = BT.connect(clientName);
  22.  
  23.     if(connected) {
  24.       Serial.println("¡Conectado exitosamente!");
  25.  
  26.       // Pause the task until bluetooth is disconnected again
  27.       vTaskSuspend(NULL);
  28.     }
  29.     else {
  30.       Serial.println("No se pudo conectar. Asegúrese de que el dispositivo remoto esté disponible y dentro del alcance.");
  31.  
  32.       // Wait a second to retry the connection
  33.       vTaskDelay( pdMS_TO_TICKS(1000) );
  34.     }
  35.   }
  36. }
  37.  
  38. void setup() {
  39.   Serial.begin(9600); // Inicialización de la conexión en serie para la depuración
  40.   BT.begin("ESP32_client", true); // Nombre de su dispositivo Bluetooth y en modo maestro
  41.   Serial.println("El dispositivo Bluetooth está en modo maestro. Conectando con el anfitrión ...");
  42.  
  43.   BT.register_callback(callback_function);
  44.  
  45.   xTaskCreatePinnedToCore(
  46.     ConnectBluetooth, // Function to call
  47.     "ConnectBluetooth", // Name for this task, mainly for debug
  48.     1024, // Stack size
  49.     NULL, // pvParameters to pass to the function
  50.     1, // Priority
  51.     &ConnectBluetoothHandle, // Task handler to use
  52.     1
  53.   );
  54. }
  55.  
  56. void loop() {
  57.   if (connected) {
  58.     delay(500);
  59.     BT.write(49); // Envía 1 en ASCII
  60.     delay(500);
  61.     BT.write(48); // Envía 0 en ASCII
  62.   }
  63.   else {
  64.     delay(1000);
  65.   }
  66. }
  67.  
  68. void callback_function(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
  69.   if (event == ESP_SPP_CLOSE_EVT  ) {
  70.     Serial.println("Cliente desconectado. Activando función de reconexión.");
  71.     vTaskResume(ConnectBluetoothHandle);    
  72.   }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement