esp32蓝牙连接手机代码
时间: 2023-08-24 10:07:13 浏览: 96
你可以尝试以下代码:
```
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
// 定义服务和特征
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
BLECharacteristic *characteristic;
bool deviceConnected = false;
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
void setup() {
// 创建 BLE 设备
BLEDevice::init("ESP32 BLE Server");
// 创建 BLE 服务
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// 创建 BLE 特征
BLEService *pService = pServer->createService(SERVICE_UUID);
characteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
// 开始服务
pService->start();
// 开始广播
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->start();
}
void loop() {
if (deviceConnected) {
// 更新特征
characteristic->setValue("Hello, World!");
characteristic->notify();
}
delay(1000);
}
```
这是一个基本的 ESP32 BLE Server 代码示例,建立了一个名为 "ESP32 BLE Server" 的 BLE 设备,并创建了一个服务和特征。可以通过特征进行读写操作,并可以通知和指示特征变化。
如果您想要连接到这个服务,您需要使用一个 BLE 客户端应用程序,并扫描设备。一旦发现设备,您可以连接到该设备并与特征进行通信。
阅读全文