BLE CC2541在一段时间后与应用程序断开连接。
创始人
2024-12-22 13:00:09
0

在使用BLE CC2541模块时,有时候会遇到与应用程序断开连接的问题。这个问题可能是由于信号弱、设备超出范围、电池电量低等原因导致的。下面是一个示例代码,用于解决BLE CC2541在一段时间后与应用程序断开连接的问题:

#include 
#include 
#include 
#include 
#include 
#include 

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
Adafruit_BMP280 bmp;

class MyServerCallbacks : public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};

void setup() {
  Serial.begin(115200);

  bmp.begin(0x76);  //初始化BMP280

  BLEDevice::init("MyDevice");
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  BLEService *pService = pServer->createService(SERVICE_UUID);
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID,
                      BLECharacteristic::PROPERTY_READ |
                      BLECharacteristic::PROPERTY_NOTIFY
                    );

  pService->start();

  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->start();
}

void loop() {
  if (deviceConnected) {
    float temperature = bmp.readTemperature();
    pCharacteristic->setValue((uint8_t*)&temperature, sizeof(temperature));
    pCharacteristic->notify();
    delay(1000);
  }

  if (!deviceConnected && oldDeviceConnected) {
    delay(500);
    pServer->startAdvertising();
    oldDeviceConnected = deviceConnected;
  }

  if (deviceConnected && !oldDeviceConnected) {
    oldDeviceConnected = deviceConnected;
  }
}

上述代码中,我们使用了BLEDevice库来初始化BLE设备,使用BLEServer和BLECharacteristic来创建服务和特征。在MyServerCallbacks类中,我们重写了onConnect()onDisconnect()函数,在连接和断开连接时设置deviceConnected变量的值。在主循环中,我们检查deviceConnected变量的值,如果设备连接上了,就读取传感器数据并通过特征通知给应用程序;如果设备断开连接了,就重新开始广播。

这样的设计可以解决BLE CC2541在一段时间后与应用程序断开连接的问题。当设备断开连接时,它会自动重新开始广播,等待应用程序重新连接。

相关内容

热门资讯

实测发现!werplan有挂吗... 实测发现!werplan有挂吗(透视)原来有挂(2022已更新)(哔哩哔哩);1、werplan有挂...
指南书辅助挂!aapoker能... 指南书辅助挂!aapoker能控制牌吗(AAPoKER)aapoker怎么拿好牌(本来真的是有挂)a...
查到实测辅助!佛手在线有挂吗(... 查到实测辅助!佛手在线有挂吗(透视)果然是有挂(2024已更新)(哔哩哔哩)亲,关键说明,佛手在线有...
资料辅助挂!aapoker透视... 资料辅助挂!aapoker透视脚本下载(aAPOKER)aapoker透视脚本下载(一贯真的有挂);...
科普分享!pokemmo手机脚... 科普分享!pokemmo手机脚本辅助器(透视)一贯存在有挂(2025已更新)(哔哩哔哩)pokemm...
妙计辅助挂!aapoker俱乐... 妙计辅助挂!aapoker俱乐部靠谱吗(Aapoker)aapoker能控制牌吗(本来真的是有挂);...
推荐十款!德州透视插件(透视)... 推荐十款!德州透视插件(透视)竟然是真的有挂(2026已更新)(哔哩哔哩)1、德州透视插件系统规律教...
策略辅助挂!aapoker辅助... 策略辅助挂!aapoker辅助工具安全吗(AAPOkER)aapoker透视方法(其实是有挂);1、...
推荐十款!pokermaste... 推荐十款!pokermaster脚本(透视)一直真的是有挂(2025已更新)(哔哩哔哩)1、poke...
演示辅助挂!aapoker怎么... 演示辅助挂!aapoker怎么开辅助器(aapoker)aapoker怎么设置抽水(其实有挂)1)a...