🛠 Moniteur de batterie BLE
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
- 1 ESP32 DevKit v1 board
- 1 Android or iOS smartphone with the nRF Connect app
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
- Forgetting BLE2902 (the CCCD descriptor): the subscription is grayed out in nRF Connect, and no notifications are sent.
- Sending multiple bytes to setValue when the profile expects a 0-100 integer on a single byte.
- Service not started (forgetting service->start): the peripheral is visible but has no service.
- Running a large BLE scan in parallel with a Wi-Fi transfer: coexistence on the single radio increases BLE latencies.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino