使用 Arduino 开发,下载 Arduino 之后,需要配置环境,在工具中选择开发板 ESP32 Dev Module
image.png

BLEScan

扫描周围的蓝牙设备,一个官方的示例:BLE_scan
image.png

  1. #include <BLEDevice.h>
  2. #include <BLEUtils.h>
  3. #include <BLEScan.h>
  4. #include <BLEAdvertisedDevice.h>
  5. int scanTime = 5;
  6. BLEScan* pBLEScan;
  7. //扫描结果回调
  8. class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
  9. void onResult(BLEAdvertisedDevice advertisedDevice) {
  10. Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
  11. }//打印相关的信息
  12. };
  13. void setup() {
  14. Serial.begin(115200);//设置波特率
  15. Serial.println("Scanning...");
  16. BLEDevice::init("");//设备初始化
  17. pBLEScan = BLEDevice::getScan(); //创建一个扫描
  18. pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  19. //设置回调函数
  20. pBLEScan->setActiveScan(true); //扫描模式,true是主动扫描,false是被动扫描
  21. pBLEScan->setInterval(100);//扫描间隔
  22. pBLEScan->setWindow(99); //扫描窗口
  23. //扫描间隔是扫描窗口加休息时间,如果扫描窗口等于扫描间隔就是不停的扫描
  24. }
  25. void loop() {
  26. // put your main code here, to run repeatedly:
  27. BLEScanResults foundDevices = pBLEScan->start(scanTime, false);//开始扫描
  28. Serial.print("Devices found: ");
  29. Serial.println(foundDevices.getCount());
  30. Serial.println("Scan done!");
  31. pBLEScan->clearResults(); //清除结果
  32. delay(2000);
  33. }

扫描结果放在 BLEScanResults,记录了每个设备和总数量,

getCount()

用来获取扫描到的设备总数量

getDevice(int)

用来通过序号获取设备,然后通过 .toString().c_str() 可以直接打印出相关信息,比如 name、address 等,每个设备都是 BLEAdvertisedDevice 对象,可以通过 BLEAdvertisedDevice 来进行相关的操作

BLEAdvertisedDevice

BLEAdvertisedDevice 是一个类,表示广播设备,对于扫描到的 BLE 设备有一些方法可以获得一些数据

getAddress()

获取广播设备地址

  1. BLEAdvertisedDevice mydevice = foundDevices.getDevice(0);
  2. Serial.printf("[+]ADDRESS:%s \n",mydevice.getAddress().toString().c_str());

getName()

获取广播设备的名字

  1. BLEAdvertisedDevice mydevice = foundDevices.getDevice(0);
  2. Serial.printf("[+]NAME:%s \n",mydevice.getName().c_str());