BLE continuous monitoring and connect when disconnected

Hi,

Need to use Arduino board (MKR 1010) as BLE Central. I do have battery BMS publishing data using BLE and want to subscribe for the same and process. While have setup the subscribe mode, for various reason the BMS BLE might disconnect and reconnect. Want a continuous monitoring and reconnect.

Here is the code -- will this cause any strain on the Arduino.

*** CODE STARTS FROM HERE ****

#include <ArduinoBLE.h>

int disconnectFlag = 1;

void setup() {
Serial.begin(9600);
while (!Serial);

// begin initialization
if (!BLE.begin()) {
Serial.println("starting BLE failed!");

while (1);

}

Serial.println("BLE Central - Peripheral Explorer");

// start scanning for peripherals
BLE.scanForName("JEPL15S02849");

}

void loop() {
// check if a peripheral has been discovered

        BLEDevice peripheral = BLE.available();
        if (peripheral) 
        {
           disconnectFlag=0;
           Serial.println(peripheral.localName());
           BLE.stopScan();
           explorerPeripheral(peripheral);
        }

}

void explorerPeripheral(BLEDevice peripheral) {
// connect to the peripheral

while (1){
//Serial.println("Connecting ...");

      if (!peripheral.connect()) {
        Serial.println("Failed to connect!");
        continue;
      }
    peripheral.discoverService("0000fff0-0000-1000-8000-00805f9b34fb");
    BLECharacteristic timeCharacteristic = peripheral.characteristic("00002902-0000-1000-8000-00805f9b34fb"); 
    byte readData;
    Serial.println("Subscribing to CurrentTime  characteristic ...");
    if (!timeCharacteristic) {
          //Serial.println("no CurrentTime  characteristic  found!");
          peripheral.disconnect();
          continue;
    } 
    else {
                if (!timeCharacteristic.subscribe()) {
                        //Serial.println("subscription failed!");
                        peripheral.disconnect();
                        continue;
                 } 
                 else {
                          Serial.println("Subscribed");
                 }
  
     }
     while (peripheral.connected()) {
        
              if (timeCharacteristic.valueUpdated()) {
                    timeCharacteristic.readValue(readData);
                    Serial.print(readData, HEX);
                    Serial.print("  : NextData = ");
                    Serial.println("");
              }
        
     }

}

}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.