使用 Arduino 开发,下载 Arduino 之后,需要配置环境 ,在工具中选择开发板 ESP32 Dev Module
image.png
BLEScan 扫描周围的蓝牙设备,一个官方的示例:BLE_scan
image.png
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 #include <BLEDevice.h> #include <BLEUtils.h> #include <BLEScan.h> #include <BLEAdvertisedDevice.h> int scanTime = 5 ;BLEScan* pBLEScan; 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 ("Scanning..." ); BLEDevice::init("" ); pBLEScan = BLEDevice::getScan(); pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); pBLEScan->setActiveScan(true ); pBLEScan->setInterval(100 ); pBLEScan->setWindow(99 ); } void loop () { BLEScanResults foundDevices = pBLEScan->start(scanTime, false ); Serial .print ("Devices found: " ); Serial .println (foundDevices.getCount()); Serial .println ("Scan done!" ); pBLEScan->clearResults(); delay (2000 ); }
扫描结果放在 BLEScanResults,记录了每个设备和总数量,
getCount() 用来获取扫描到的设备总数量
getDevice(int) 用来通过序号获取设备,然后通过 .toString().c_str() 可以直接打印出相关信息,比如 name、address 等,每个设备都是 BLEAdvertisedDevice 对象,可以通过 BLEAdvertisedDevice 来进行相关的操作
BLEAdvertisedDevice BLEAdvertisedDevice 是一个类,表示广播设备,对于扫描到的 BLE 设备有一些方法可以获得一些数据
getAddress() 获取广播设备地址
1 2 BLEAdvertisedDevice mydevice = foundDevices.getDevice(0 ); Serial.printf("[+]ADDRESS:%s \n" ,mydevice.getAddress().toString().c_str());
getName() 获取广播设备的名字
1 2 BLEAdvertisedDevice mydevice = foundDevices.getDevice(0 ); Serial.printf("[+]NAME:%s \n" ,mydevice.getName().c_str());
最后更新时间:2022-10-03 21:52:43