こちらと同様のことを、ArduinoBLE.h を使って行いました。
ESP32: GATT通信
スケッチ例を参考にしました。
プログラム
BatteryMonitor.ino
// ---------------------------------------------------------------
/*
BatteryMonitor.ino
Sep/22/2024
*/
// ---------------------------------------------------------------
#include <ArduinoBLE.h>
BLEService batteryService("180F");
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
int icount = 0;
// ---------------------------------------------------------------
void setup() {
Serial.begin(115200);
while (!Serial);
if (!BLE.begin()) {
Serial.println("starting BLE failed!");
while (1);
}
BLE.setLocalName("BatteryMonitor");
BLE.setAdvertisedService(batteryService); // add the service UUID
batteryService.addCharacteristic(batteryLevelChar); // add the battery level characteristic
BLE.addService(batteryService);
int oldBatteryLevel = 0;
batteryLevelChar.writeValue(oldBatteryLevel);
BLE.advertise();
Serial.println("Bluetooth® device active, waiting for connections...");
}
// ---------------------------------------------------------------
void loop() {
Serial.print("*** loop *** ");
Serial.println(icount);
icount++;
delay(1000);
// wait for a Bluetooth® Low Energy central
BLEDevice central = BLE.central();
// if a central is connected to the peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's BT address:
Serial.println(central.address());
if (central.connected()) {
updateBatteryLevel();
}
}
else
{
Serial.print("Disconnected from central: ");
Serial.println(central.address());
}
}
// ---------------------------------------------------------------
void updateBatteryLevel() {
int batteryLevel = 25 + icount;
Serial.print("Battery Level % is now: "); // print it
Serial.println(batteryLevel);
batteryLevelChar.writeValue(batteryLevel);
}
// ---------------------------------------------------------------