 #include <BLEUtils.h>
 #include <BLE2902.h>
 
+BLEServer *pServer = NULL;
 BLECharacteristic *pCharacteristic;
 bool deviceConnected = false;
+bool oldDeviceConnected = false;
 uint8_t value = 0;
 
 // See the following for generating UUIDs:

  BLEDevice::init("MyESP32");

  // Create the BLE Server
  BLEServer *pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service

}

void loop() {
    // notify changed value
    if (pCharacteristic->isReadyForData()) {
        pCharacteristic->setValue(&value, 1);
        pCharacteristic->notify();
        value++;
        delay(10); // bluetooth stack will go into congestion, if too many packets are sent
    }
    // disconnecting
    if (!deviceConnected && oldDeviceConnected) {
        delay(500); // give the bluetooth stack the chance to get things ready
        pServer->startAdvertising(); // restart advertising
        Serial.println("start advertising");
        oldDeviceConnected = deviceConnected;
    }
    // connecting
    if (deviceConnected && !oldDeviceConnected) {
        // do stuff here on connecting
        oldDeviceConnected = deviceConnected;
    }
}