BLE扫描仅在第一次扫描时获得某些设备的名称

时间:2020-01-26 20:07:33

标签: arduino bluetooth-lowenergy esp32

我有以下代码:

#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEAdvertisedDevice.h>

static void log(String message) {
  Serial.println(message);
}

const char* deviceName = "BLEScanner";
BLEScan* pBLEScan;

void setup() {
  Serial.begin(115200);   
  log("Setup!");
  BLEDevice::init(deviceName);
  pBLEScan = BLEDevice::getScan(); //create new scan
  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() {
  log("Listing BLE Sensors");
  BLEScanResults foundSensors = pBLEScan->start(30, false);
  int count = foundSensors.getCount();
  for (int i = 0; i < count; i++) {
    BLEAdvertisedDevice bleSensor = foundSensors.getDevice(i);
    String sensorName = bleSensor.getName().c_str();
    String address = bleSensor.getAddress().toString().c_str();
    log(address + " " + sensorName);
  }
  log("Sleeping");
  sleep(10);
}

运行时,我得到以下输出:

Setup!
Listing BLE Sensors
00:09:b0:09:e7:ca 
41:59:8f:07:ec:96
ac:5d:5c:e1:72:89 LM0845
c4:7c:8d:6a:36:cf Flower care
c4:7c:8d:6a:45:6b Flower care
c4:7c:8d:6a:46:2c Flower care
de:d5:2a:8e:1e:fd Tile
Sleeping
Listing BLE Sensors
00:09:b0:09:e7:ca 
41:59:8f:07:ec:96
ac:5d:5c:e1:72:89
dc4:7c:8d:6a:36:cf
dc4:7c:8d:6a:45:6b
dc4:7c:8d:6a:46:2c
de:d5:2a:8e:1e:fd Tile
Sleeping
Listing BLE Sensors
00:09:b0:09:e7:ca 
41:59:8f:07:ec:96
ac:5d:5c:e1:72:89
c4:7c:8d:6a:36:cf
dc4:7c:8d:6a:45:6b
dc4:7c:8d:6a:46:2c
de:d5:2a:8e:1e:fd Tile
... and so on

由于某种原因,我第一次只获得某些设备的名称,这是一个已知错误,该如何解决?

我尝试在开始扫描之前放入pBLEScan->clearResults();,但这没有帮助。

我正在使用ESP32 Adafruit羽毛。

我发现的唯一解决方案是将BLEDevice::init(deviceName);放入循环中,然后在睡眠前运行BLEDevice::deinit();

0 个答案:

没有答案