🛠 Moniteur de batterie BLE

ESP32 (original, ESP32-WROOM-32 class) · intermediaire · Schéma : IMG-esp32-intermediaire-2-ble-batterie-monitor.svg — ESP32 émettant un service BLE Battery 0x180F vers un smartphone affichant le pourcentage

Objectives

Create a BLE (Bluetooth Low Energy) peripheral compliant with the standard Battery Service profile (UUID 0x180F, characteristic 0x2A19) that any generic application can read. You will learn the server / service / characteristic triad, notifications, and the CCCD descriptor. Reminder: the ESP32's BLE radio shares the single 2.4 GHz radio and antenna with Wi-Fi.

Hardware

Complete code

#include <WiFi.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLECharacteristic* cBatterie;
uint8_t niveau = 100;

void setup {
  Serial.begin(115200);
  BLEDevice::init("ESP32-Batterie");
  BLEServer* serveur = BLEDevice::createServer;
  BLEService* service = serveur->createService("180F");   // Battery Service
  cBatterie = service->createCharacteristic("2A19",
      BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
  cBatterie->addDescriptor(new BLE2902);               // CCCD obligatoire
  service->start;
  BLEAdvertising* adv = BLEDevice::getAdvertising;
  adv->addServiceUUID("180F");
  adv->start;
  Serial.println(F("BLE pret : cherchez ESP32-Batterie"));
}

void loop {
  niveau = (uint8_t)(50 + 49 * sin(millis / 20000.0f)); // simulation
  cBatterie->setValue(&niveau, 1);
  cBatterie->notify;
  Serial.printf("Niveau annonce : %d %%\n", niveau);
  delay(2000);
}

Expected verification

nRF Connect lists "ESP32-Batterie"; by opening service 0x180F and then subscribing (notify icon) to characteristic 0x2A19, the displayed value oscillates between 1 and 99% every 2 seconds.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials