I am using Arduino to program ESP32.
I am very new to BLE but have been working with Arduino for a long time. My knowledge on BLE is limited to https://www.youtube.com/watch?v=2mePPqiocUE this video.
My idea here is to program the ESP32 as a server which uses GAT services to display the battery level on my phone (client) when the bluetooth connection is paired. I am partially successful with the below code
Code: Select all
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>
byte percentage = byte(62);
byte level[1] = {percentage};
bool _BLEClientConnected = false;
#define BatteryService BLEUUID((uint16_t)0x180F)
BLECharacteristic BatteryLevelCharacteristic(BLEUUID((uint16_t)0x2A19), BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
BLEDescriptor BatteryLevelDescriptor(BLEUUID((uint16_t)0x2901));
class MyServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
_BLEClientConnected = true;
};
void onDisconnect(BLEServer* pServer) {
_BLEClientConnected = false;
}
};
void InitBLE() {
BLEDevice::init("BLE Battery");
// Create the BLE Server
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pBattery = pServer->createService(BatteryService);
pBattery->addCharacteristic(&BatteryLevelCharacteristic);
BatteryLevelDescriptor.setValue("Percentage 0 - 100");
BatteryLevelCharacteristic.addDescriptor(&BatteryLevelDescriptor);
BatteryLevelCharacteristic.addDescriptor(new BLE2902());
pServer->getAdvertising()->addServiceUUID(BatteryService);
pBattery->start();
// Start advertising
pServer->getAdvertising()->start();
}
void setup() {
Serial.begin(115200);
Serial.println("Battery Level Indicator - BLE");
InitBLE();
}
void loop() {
BatteryLevelCharacteristic.setValue(level, 1);
BatteryLevelCharacteristic.notify();
delay(2000);
percentage++;
level[1] = (byte)percentage;
Serial.println(level[1]);
}
I am using nRF mobile application to monitor the BLE server and there I am able to receive the data that was initialized, I am not getting it to update for every 2 sec, it stays at 62% as shown below.
I am also a bit confused on the characteristic function Read and Notify. What does it mean why is notify optional? Also since we are writing the battery level from server to client should it not be write instead of Read?