低功耗蓝牙:
低功耗蓝牙,简称 BLE,是蓝牙的省电版本。BLE 的主要应用是短距离传输少量数据(低带宽)。与经典蓝牙不同,BLE 始终保持睡眠模式,除非启动连接,这使得它消耗的功率非常低。
下面是 BLE 与经典蓝牙对比:
使用低功耗蓝牙,有两种类型的设备:服务器和客户端。ESP32 既可以作为客户端,也可以作为服务器。
BLE支持点对点通信、广播模式和网状网络:
- 点对点通信:服务器蓝牙需要主动广播信号,以便其他设备找到它,其中包含客户端可以读取的数据。客户端蓝牙需要扫描附近的设备,当找到它要查找的服务器时,建立连接并侦听传入的数据;
- 广播模式:服务器将数据传输到连接的多个客户端;
- 网状网络:所有设备都已连接,这是多对多的连接。
-
ESP32 BLE 服务器:
- 创建 BLE 服务器;
- 创建 BLE 服务;
- 在服务上创建 BLE 特征;
- 在特征上创建 BLE 描述符;
- 启动服务;
- 开始广播,以便其他设备找到它。
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
// Service 和 Character 定义一个 UUID
// UUID 用于标识蓝牙服务以及特征访问属性
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
void setup()
{
Serial.begin(115200);
Serial.println("Starting BLE work!");
BLEDevice::init("Long name now"); // 创建名字为“Long name now”的 BLE 设备
BLEServer *pServer = BLEDevice::createServer(); // 将 BLE 设备设置为服务器
BLEService *pService = pServer->createService(SERVICE_UUID); // 前面定义的 UUID 为 BLE 服务器创建服务
BLECharacteristic *pCharacteristic = pService->createCharacteristic( // 设置服务特征
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
pCharacteristic->setValue("I am BEL"); // 发送
pService->start(); // 启动服务
// BLEAdvertising *pAdvertising = pServer->getAdvertising(); // 检索可用于发布服务器存在的发布对象
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true); // 响应
pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
Serial.println("Characteristic defined! Now you can read it in your phone!");
}
void loop()
{
delay(2000);
}
ESP32 BLE 客户端:
#include <Arduino.h>
#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(""); // 初始化 BLE 设备
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(); // 从 blescan 缓冲区中删除结果以释放内存
delay(2000);
}
两个 ESP32 分别烧录上面程序就可以在客户端发现服务器端。
扫描一下找到了好多......但也有我需要的服务器端。