Skip to content

Doesn't detect the bluetooth service in every loop #223

Open
@eddydecena

Description

@eddydecena

Hi! I'm trying to detect in every loop in Arduino if there is a Bluetooth service active in a Bluetooth device but most of the time ArduinoBLE does not detect any service even though the service is running in the Bluetooth devices.

Code:

#include <ArduinoBLE.h>

const char* BLE_SERVICE_NAME = "Eddy Decena";

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

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

    while (1);
  }

  Serial.println("BLE Central scan");

  // start scanning for peripheral
  // Use BLE.scan(); may be more faster then BLE.scanForName(BLE_SERVICE_NAME); for more then one key
  BLE.scanForName(BLE_SERVICE_NAME);
}

void loop() {
  // check if a peripheral has been discovered
  BLEDevice peripheral = BLE.available();
  Serial.println(peripheral);

  if (peripheral) {
    // ** debug code **
    // discovered a peripheral
    Serial.println("Discovered peripheral");
    Serial.println("-----------------------");

    // print address
    Serial.print("Address: ");
    Serial.println(peripheral.address());

    // print the local name, if present
    if (peripheral.hasLocalName()) {
      Serial.print("Local Name: ");
      Serial.println(peripheral.localName());
    } else {
      return; // skip the actual code if doesn't has local name
    }

    // print the advertised service UUIDs, if present
    if (peripheral.hasAdvertisedServiceUuid()) {
      Serial.print("Service UUIDs: ");
      for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
        Serial.print(peripheral.advertisedServiceUuid(i));
        Serial.print(" ");
      }
      Serial.println();
    }

    // print the RSSI
    Serial.print("RSSI: ");
    Serial.println(peripheral.rssi());
    Serial.println();
    // ** debug code **

    // ** actual code **
    if (peripheral.localName() == BLE_SERVICE_NAME){
      Serial.println("Connecting ...");

      if (peripheral.connect()) {
        Serial.println("Connected");
      } else {
        Serial.println("Failed to connect!");
        return;
      }
    }
    // ** actual code **
  }
}

In this code the variable peripheral, inside the loop function, should be 1 if there is a Bluetooth service with the name Eddy Decena but most of the time it comes like 0 even though the service is running.

I need to be able to confirm if there is a service running with the name Eddy Decena in every loop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: codeRelated to content of the project itselftype: imperfectionPerceived defect in any part of project

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions