蓝牙低功耗(BLE)是ESP32支持的重要无线通信协议,具有低功耗、快速连接的特点。
BLE设备通过广播数据包被发现,广播数据包含设备名称、服务UUID等信息。
ESP32设置BLE广播的基本步骤:
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
void setup() {
BLEDevice::init("ESP32_BLE_Device");
BLEServer *pServer = BLEDevice::createServer();
// 创建广播对象
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06); // 有助于iPhone连接
pAdvertising->setMinPreferred(0x12);
// 开始广播
pAdvertising->start();
}
GATT(Generic Attribute Profile)定义了BLE设备间数据传输的方式:
// 创建服务
BLEService *pService = pServer->createService(SERVICE_UUID);
// 创建特征值
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY
);
// 添加描述符
pCharacteristic->addDescriptor(new BLE2902());
// 启动服务
pService->start();
ESP32支持经典蓝牙(Bluetooth Classic),可实现SPP(Serial Port Profile)串口透传功能。
注意:经典蓝牙相比BLE功耗更高,适合需要较高数据传输速率的应用。
ESP32设置SPP串口透传的基本步骤:
#include "BluetoothSerial.h"
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32_SPP"); // 蓝牙设备名称
Serial.println("蓝牙设备已启动,等待连接...");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
SPP连接过程:
为提高SPP传输效率,可采取以下措施:
// 设置PIN码增加安全性
SerialBT.setPin("1234");
// 检查连接状态
if(SerialBT.connected()) {
// 发送数据
SerialBT.println("Hello from ESP32!");
}
客服小姐姐(优先添加)
讲师微信(备用)