Pokhraj Das
Pokhraj Das

Reputation: 21

How to Get the RSSI value for Multiple devices while scan by ESP32

I am using the below code to get the RSSI value. I am able to get the value successfully for one Device at a time. But I am confused about how to get the RSSI value for multiple devices while scanning by ESP32. The below code snippet I am using.

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

int scanTime = 10; //In seconds
BLEScan* pBLEScan;

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
      Serial.print(" RSSI: ");
      Serial.println(advertisedDevice.getRSSI());
    }
};

void setup() {
  Serial.begin(115200);
  Serial.println("Scanning...");
  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan(); //create new scan
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);  // less or equal setInterval value
 
}

void loop() {
  // put your main code here, to run repeatedly:
  BLEScanResults foundDevices = pBLEScan->start(scanTime, true);
  Serial.print("Devices found: ");
  Serial.println(foundDevices.getCount());
 
  // you can access first device with foundDevices.getDevice(0).getAddress()
  
  Serial.println("Scan done!");
  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
  delay(2000);
}

Can anyone advice how Do I get the multiple RSSI value while scanning devices

Upvotes: 2

Views: 454

Answers (1)

jonathan
jonathan

Reputation: 44

The issue with your code is that you're using a blocking scan pBLEScan->start(scanTime, true); but relying on the onResult() callback. In a blocking scan, the onResult() callback doesn't get called as you'd expect, so you end up with the RSSI value for only one device.

To fix this:

  • After the scan completes, use foundDevices.getCount() to find out how many devices were discovered.
  • Loop through the discovered devices using a for-loop.
  • For each device, use foundDevices.getDevice(i) to access it.
  • Get the RSSI for each device by calling getRSSI().

Upvotes: 0

Related Questions