基于 Arduino 编写 ESP32 BLE Server 例程

测试代码如下:

  • 支持 BLE 连接
  • 支持 BLE 数据传输
#include 
#include 
#include 

namespace BLEServerDemo {

BLEServer *pServer = nullptr;
BLEService *pService = nullptr;
BLECharacteristic *pCharacteristic = nullptr;

bool deviceConnected = false;

class ServerCallbacks : public BLEServerCallbacks {
  void onConnect(BLEServer *pServer) {
    deviceConnected = true;
    Serial.println("BLE connected");
  }

  void onDisconnect(BLEServer *pServer) {
    deviceConnected = false;
    Serial.println("BLE disconnected");
    pServer->startAdvertising();  // Restart advertising after disconnection
  }
};

class CharacteristicCallbacks : public BLECharacteristicCallbacks {
  void onWrite(BLECharacteristic *pCharacteristic) {
    std::string value = pCharacteristic->getValue();
    
    Serial.print("Received Value: ");
  for (int i = 0; i < value.length(); i++) {
     // Serial.print(value[i]);
      Serial.print(value[i],HEX);
      Serial.print(" ");
    }
    Serial.println();
  }
};

void initBLE() {
  BLEDevice::init("MyESP32BLEServer");
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new ServerCallbacks());

  pService = pServer->createService(BLEUUID("0000fff0-0000-1000-8000-00805f9b34fb"));

  pCharacteristic = pService->createCharacteristic(
      BLEUUID("0000fff1-0000-1000-8000-00805f9b34fb"),
      BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE
  );
  pCharacteristic->setCallbacks(new CharacteristicCallbacks());

  pService->start();
  pServer->getAdvertising()->start();
  Serial.println("Waiting for client connection...");
}

void handleBLE() {
  if (deviceConnected) {
    // Handle other tasks as needed
  }
}

}  // namespace BLEServerDemo

void setup() {
  Serial.begin(115200);
  BLEServerDemo::initBLE();
}

void loop() {
  BLEServerDemo::handleBLE();
}

你可能感兴趣的:(ESP,应用需求实现,c语言)