ESP32-C6 Bluetooth scanner example

Hi there,
I like this for compactness,
Uses a vector to store the info if it has a name, other wise it’s skipped.
here is the code,

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <vector>
#include <algorithm>

// Struct to store BLE device name and RSSI
struct BLEDeviceInfo {
  String deviceName;
  int rssi;
};

// Vector to store devices
std::vector<BLEDeviceInfo> devices;

// Scan time in seconds
int scanTime = 30;
BLEScan *pBLEScan;

// Custom callback class to handle found devices
class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    if (advertisedDevice.haveName()) {  // Only store if the device has a name
      BLEDeviceInfo dev;
      dev.deviceName = advertisedDevice.getName().c_str();
      dev.rssi = advertisedDevice.getRSSI();
      devices.push_back(dev);  // Store device name and RSSI in vector
    }
  }
};

void setup() {
  Serial.begin(9600);
  delay (2000);
   Serial.println();
  Serial.println("Power ON \n ");  // Let's BEGIN!!
  Serial.println("Test program compiled on " __DATE__ " at " __TIME__);
  Serial.println();
  Serial.println("Processor came out of reset.");
  Serial.println("Scanning...");

  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan();  // Create new scan
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true);    // Active scan uses more power, but gets results faster
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);          // Less or equal to setInterval value
}

void loop() {
  // Clear devices vector
  devices.clear();

  // Start BLE scan
  pBLEScan->start(scanTime, false);

  // Sort devices by RSSI in descending order
  std::sort(devices.begin(), devices.end(), [](const BLEDeviceInfo &a, const BLEDeviceInfo &b) {
    return a.rssi > b.rssi;
  });

  // Print sorted devices with names and RSSI
  Serial.println("Devices found (sorted by RSSI):");
  for (const auto &device : devices) {
    Serial.printf("Device Name: %s, RSSI: %d\n", device.deviceName.c_str(), device.rssi);
  }

  Serial.println("Scan done!");
  pBLEScan->clearResults();  // Clear results from the BLE scan buffer to release memory

  delay(2000);
}

and her is the output,

Power ON 
 
Test program compiled on Sep 19 2024 at 00:47:46

Processor came out of reset.
Scanning...
Devices found (sorted by RSSI):
Device Name: iTrack, RSSI: -65
Device Name: iTrack, RSSI: -68
Scan done!

HTH
GL :slight_smile: PJ :v:

FQBN: esp32:esp32:XIAO_ESP32C6
Using board ‘XIAO_ESP32C6’ from platform in folder: C:\Users\Dude\AppData\Local\Arduino15\packages\esp32\hardware\esp32\3.0.4
Using core ‘esp32’ from platform in folder: C:\Users\Dude\AppData\Local\Arduino15\packages\esp32\hardware\esp32\3.0.4