🛠 Service batterie BLE 5 avec notification

ESP32-S3 · intermediaire · Schéma : IMG-esp32-s3-intermediaire-2-esp32-s3-ble5-service-batterie.svg — Carte ESP32-S3 émettant des ondes BLE vers un smartphone affichant le niveau de batterie, avec la mention Bluetooth 5 LE, Coded PHY et 2 Mbps.

Objectives

Leverage the Bluetooth 5 LE of the ESP32-S3 (absent in the classic ESP32, which only has BLE 4.2) by exposing the standard Battery service (UUID 0x180F) with its Level characteristic (0x2A19) for reading and notifications. You will use the BLE stack embedded in the Arduino core (BLEDevice/NimBLE), declare the service in the advertising, and simulate a battery level drop followed by notifications to a smartphone equipped with an app like "nRF Connect".

Hardware

Complete code

// Service batterie BLE 5 : UUID 180F / niveau 2A19 en READ + NOTIFY
#include "BLEDevice.h"
#include "BLEServer.h"
#include "BLEUtils.h"
#include "BLE2902.h"

BLECharacteristic* pLevel = nullptr;
uint8_t percent = 100;
uint32_t derniereNotif = 0;

class ServCb : public BLEServerCallbacks {
  void onConnect(BLEServer* s) override { Serial.println("Client connecte"); }
  void onDisconnect(BLEServer* s) override {
    Serial.println("Client deconnecte, reprise advertising");
    BLEDevice::getAdvertising->start;   // indispensable
  }
};

void setup {
  Serial.begin(115200);
  BLEDevice::init("S3-batterie");
  BLEServer* srv = BLEDevice::createServer;
  srv->setCallbacks(new ServCb);

  BLEService* bat = srv->createService("180F");          // Battery
  pLevel = bat->createCharacteristic("2A19",
      BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
  pLevel->addDescriptor(new BLE2902);                   // CCCD
  pLevel->setValue(&percent, 1);
  bat->start;

  BLEAdvertising* adv = BLEDevice::getAdvertising;
  adv->addServiceUUID("180F");
  adv->setScanResponse(true);
  adv->start;
  Serial.println("Advertising S3-batterie lance");
}

void loop {
  if (millis - derniereNotif > 5000) {
    derniereNotif = millis;
    percent = percent > 0 ? percent - 1 : 100;   // fausse descente
    pLevel->setValue(&percent, 1);
    pLevel->notify;
    Serial.printf("niveau = %u %%\n", percent);
  }
  delay(100);
}

Expected verification

In nRF Connect, the "S3-batterie" device appears; connecting reveals the Battery service 180F. After subscribing (enable notifications on 2A19), the level decrementing by 1% every 5 seconds arrives in real time. The S3 supports 2 Mbps PHY and Coded PHY (long range) where a classic ESP32 remains at 1 Mbps; under NimBLE, these PHYs are configurable via the stack options.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials