ESP32, BLE, and the fix of the advertisement issues

After following a ESP32 + Bluetooth Low Energy (BLE) tutorial, my phone would only connect once to the ESP32. After it disconnected it wouldn’t reconnect. This is how I fixed it.

After a lot of tinkering I found out one thing I didn’t find in any of the tutorials I browsed through: after a BLE client connects, the BLE server will stop advertising. As a result, nRF Connect (the app I use to test on my phone) wouldn’t reconnect.

I solved it by restarting the advertising in the onConnect callback function:

class BLEServerCB : public BLEServerCallbacks {
  void onConnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param) override {
    BLEDevice::startAdvertising();
  }
} bleServerCB;

void setup() {
  BLEDevice::init(DEVICE_NAME);
  BLEServer *bleServer = BLEDevice::createServer();
  bleServer->setCallbacks(&bleServerCB);
  // ... the rest of the setup.
}

This will keep your ESP32 announcing its presence to the world, regardless of who connected in the past. Might not be what you want, but it sure helped me test things.

dr. Sybren A. Stüvel
dr. Sybren A. Stüvel
Open Source software developer, photographer, drummer, and electronics tinkerer

Related