使用 Arduino 开发,下载 Arduino 之后,需要配置环境,在工具中选择开发板 ESP32 Dev Module
BLEScan
扫描周围的蓝牙设备,一个官方的示例:BLE_scan
#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); //扫描模式,true是主动扫描,false是被动扫描pBLEScan->setInterval(100);//扫描间隔pBLEScan->setWindow(99); //扫描窗口//扫描间隔是扫描窗口加休息时间,如果扫描窗口等于扫描间隔就是不停的扫描}void loop() {// put your main code here, to run repeatedly: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()
获取广播设备地址
BLEAdvertisedDevice mydevice = foundDevices.getDevice(0);Serial.printf("[+]ADDRESS:%s \n",mydevice.getAddress().toString().c_str());
getName()
获取广播设备的名字
BLEAdvertisedDevice mydevice = foundDevices.getDevice(0);Serial.printf("[+]NAME:%s \n",mydevice.getName().c_str());
