#include<BLEDevice.h>#include<BLEServer.h>#include<BLEUtils.h>#include<BLE2902.h>
BLEServer* pServer =NULL;
BLECharacteristic* pCharacteristic =NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint32_t value =255;#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
class MyServerCallbacks: public BLEServerCallbacks {voidonConnect(BLEServer* pServer){
deviceConnected = true;};voidonDisconnect(BLEServer* pServer){
deviceConnected = false;}};voidonButton(){// sedning integer 255 via notify
pCharacteristic->setValue((uint8_t*)&value,4);
pCharacteristic->notify();}voidsetup(){
Serial.begin(115200);pinMode(0, INPUT_PULLUP);// Create the BLE Device
BLEDevice::init("ESP32");// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);// Create a BLE Characteristic
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
pCharacteristic->addDescriptor(new BLE2902());// Start the service
pService->start();// Start advertising
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
pAdvertising->setMinPreferred(0x0);// set value to 0x00 to not advertise this parameter
BLEDevice::startAdvertising();
Serial.println("Waiting a client connection to notify...");}voidloop(){// notify value no button pushedif(deviceConnected){static uint8_t lastPinState =1;
uint8_t pinState =digitalRead(0);if(!pinState && lastPinState){onButton();}
lastPinState = pinState;}// disconnectingif(!deviceConnected && oldDeviceConnected){delay(500);// give the bluetooth stack the chance to get things ready
pServer->startAdvertising();// restart advertising
Serial.println("start advertising");
oldDeviceConnected = deviceConnected;}// connectingif(deviceConnected &&!oldDeviceConnected){// do stuff here on connecting
oldDeviceConnected = deviceConnected;}}
0 件のコメント:
コメントを投稿