#include #include #include #include int scanTime = 5; // 扫描时间(单位:秒) BLEScan* pBLEScan; // BLE 扫描对象指针 // 自定义回调类,用于处理扫描到的 BLE 设备信息 class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks { void onResult(BLEAdvertisedDevice advertisedDevice) { Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str()); } }; void setup() { Serial.begin(115200); Serial.println("Starting BLE scan..."); BLEDevice::init(""); // 初始化 BLE pBLEScan = BLEDevice::getScan(); // 创建新的扫描对象 pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); // 设置回调 pBLEScan->setActiveScan(true); // 主动扫描模式(速度更快,但功耗更高) pBLEScan->setInterval(100); // 扫描间隔 pBLEScan->setWindow(99); // 扫描窗口(必须 <= interval) } void loop() { Serial.println("Scanning..."); // 扫描并获取结果(新版库返回的是指针) BLEScanResults* foundDevices = pBLEScan->start(scanTime, false); // 输出扫描结果 if (foundDevices != nullptr) { Serial.print("Devices found: "); Serial.println(foundDevices->getCount()); } else { Serial.println("No devices found or scan failed."); } Serial.println("Scan done!"); pBLEScan->clearResults(); // 清空缓存以释放内存 delay(2000); // 每2秒重复扫描一次 }