添加一个连接状态变量,然后使用该变量来检查连接状态,以便确定何时触发disconnect事件。
以下是示例代码:
#include
bool isConnected = false; // 添加"连接状态"变量
void setup() {
Serial.begin(9600);
if (!BLE.begin()) {
Serial.println("Failed to initialize BLE!");
while (1);
}
BLE.deviceConnectedCallback(deviceConnected);
BLE.deviceDisconnectedCallback(deviceDisconnected); // 添加回调函数
BLE.setLocalName("MyDevice");
BLE.setAdvertisedService(bleService);
bleService.addCharacteristic(bleCharacteristic);
BLE.addService(bleService);
BLE.advertise();
}
void loop() {
if (isConnected) { // 使用"连接状态"变量确定何时触发disconnect事件
// 执行接收/发送代码
}
}
void deviceConnected(BLEDevice central) {
isConnected = true; // 当连接时,修改"连接状态"变量
Serial.print("Connected to central: ");
Serial.println(central.address());
}
void deviceDisconnected(BLEDevice central) {
isConnected = false; // 当断开连接时,修改"连接状态"变量
Serial.print("Disconnected from central: ");
Serial.println(central.address());
}