一 可运行代码
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>
#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;
unsigned long lastAdvertisingRestart = 0;
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
Serial.println("Device connected");
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
Serial.println("Device disconnected");
}
};
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
String arduinoString = pCharacteristic->getValue();
if (arduinoString.length() > 0) {
Serial.println("Received Value: ");
Serial.println(arduinoString);
// Create simple response
String response = "{\"status\":\"OK\",\"message\":\"Data received: " + arduinoString + "\"}";
// Set the characteristic's value to the response string
pCharacteristic->setValue(response.c_str());
pCharacteristic->notify();
Serial.println("Response sent");
}
}
void onRead(BLECharacteristic *pCharacteristic) {
Serial.println("Characteristic read");
}
void onNotify(BLECharacteristic *pCharacteristic) {
Serial.println("Characteristic notified");
}
};
void setup() {
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Serial communication started");
// Create the BLE Device
BLEDevice::init("ESP32-C3");
if (!BLEDevice::getInitialized()) {
Serial.println("Failed to initialize BLE Device!");
while (1) {