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

image.png
image.png

BLEScan

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

image.png
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); //扫描模式,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()

获取广播设备地址

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());