Lesson 11
22 min
Understand BLE services and characteristics, and control the board from a phone.
Definition
Bluetooth is a short-range wireless communication technology that directly connects two devices without using a router.BLE (Bluetooth Low Energy) is a variant designed to exchange small amounts of data while consuming very little power. In BLE communication, a device called a server(here, the ESP32) exposes data organized intoservices and characteristics, which a client device (such as a smartphone) can read, write, or receive through notifications.
The classic ESP32 supports two distinct Bluetooth technologies:
This lesson focuses on BLE, which is more modern and compatible with both iOS and Android smartphones. Note that the ESP32-S2 does not support Bluetooth at all.
Although both technologies share the Bluetooth name, they are not directly compatible: a BLE-only device cannot communicate using a Bluetooth Classic connection. Bluetooth Classic remains useful for transmitting continuous data streams, for example with theBluetoothSeriallibrary, but it consumes more power and is not available on every ESP32 model. For a project that must work with an iPhone, BLE is the practical choice because iOS does not provide the standard Bluetooth Classic serial connection to applications.
BLE communication follows a specific structure, which can be compared to a restaurant:

To extend the comparison: the ESP32 is the restaurant, displaying a sign visible from the street (advertising). The smartphone is the customer entering the restaurant. Inside, the menu is divided into sections (services), and each section contains dishes (characteristics). The customer can order a dish by writingto a characteristic or inspect a dish by reading it.
When a characteristic is created, it declares which operations the client is allowed to perform. These permissions are called properties, and they can be combined using the|symbol.
PROPERTY_READ: the client can read the value whenever it wants.PROPERTY_WRITE: the client can write a new value, for example to send a command.PROPERTY_NOTIFY: the server can notify the client when the value changes, without the client having to request it again.To test BLE without writing an application, install the free nRF Connect for Mobileapp (developed by Nordic Semiconductor, available for Android and iOS). It allows you to scan for BLE devices, connect to them, and read or write their characteristics.
On Android, the application generally requests Bluetooth and location permissions to perform scanning. Grant the required permissions; otherwise, devices may not appear in the list. Also make sure your smartphone's Bluetooth is enabled.
The following program creates a BLE service with a characteristic that supports reading and writing. When the smartphone writes the character1, the LED turns on. When it writes0, the LED turns off. The BLE libraries are included in the esp32 board package.
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
const int ledPin = 2;
// Called when the smartphone writes a value
class MyCallbacks : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *characteristic) {
auto value = characteristic->getValue();
if (value.length() > 0) {
if (value[0] == '1') {
digitalWrite(ledPin, HIGH);
Serial.println("LED ON");
} else if (value[0] == '0') {
digitalWrite(ledPin, LOW);
Serial.println("LED OFF");
}
}
}
};
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
BLEDevice::init("ESP32-Course");
BLEServer *server = BLEDevice::createServer();
BLEService *service = server->createService(SERVICE_UUID);
BLECharacteristic *characteristic = service->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE
);
characteristic->setCallbacks(new MyCallbacks());
characteristic->setValue("0");
service->start();
BLEAdvertising *advertising = BLEDevice::getAdvertising();
advertising->addServiceUUID(SERVICE_UUID);
BLEDevice::startAdvertising();
Serial.println("BLE started: look for ESP32-Course in nRF Connect");
}
void loop() {
delay(2000);
}The program always follows the same configuration steps. First, BLE is initialized and the device is given a name usingBLEDevice::init(). Next, the server, a service, and a characteristic are created. A callback class is then associated with the characteristic: itsonWrite()function runs automatically whenever the smartphone writes a value. Finally, the service starts and advertising begins, making the ESP32 discoverable. Theloop()function has almost nothing to do: everything happens inside the callback.

Board Package Versions Affect the BLE Library
Between versions 2.x and 3.x of the esp32 board package, the types used by the BLE library have changed (for example,std::stringbecameString). The example above usesautoto remain compatible with both versions. However, if you copy code from the Internet and it does not compile, the board package version is the first thing to check.
This is the most common problem during a first test. Check the following points in order:
It is often useful to know whether a smartphone is connected or disconnected. This can be done using a second callback class, associated with the server, containing theonConnect()andonDisconnect()functions. In the following example, the LED remains on as long as a client is connected. Notice that advertising is restarted after disconnection: without it, the ESP32 would no longer be discoverable until the board is restarted.
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
const int ledPin = 2;
bool clientConnected = false;
class ServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer *server) {
clientConnected = true;
digitalWrite(ledPin, HIGH);
Serial.println("Client connected");
}
void onDisconnect(BLEServer *server) {
clientConnected = false;
digitalWrite(ledPin, LOW);
Serial.println("Client disconnected");
BLEDevice::startAdvertising(); // Become discoverable again
}
};
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
BLEDevice::init("ESP32-Course");
BLEServer *server = BLEDevice::createServer();
server->setCallbacks(new ServerCallbacks());
BLEService *service = server->createService(SERVICE_UUID);
BLECharacteristic *characteristic = service->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ
);
characteristic->setValue("Hello");
service->start();
BLEAdvertising *advertising = BLEDevice::getAdvertising();
advertising->addServiceUUID(SERVICE_UUID);
BLEDevice::startAdvertising();
Serial.println("Waiting for a client...");
}
void loop() {
delay(1000);
}So far, the smartphone decides when to read or write data. For a sensor that sends regular measurements, the process is reversed: the ESP32 must be able to notify the smartphone whenever a new value is available. This is the purpose of notifications. Add thePROPERTY_NOTIFYproperty to the characteristic, then callnotify()whenever a new value is available. The client must enable notifications on its side, which can be done in nRF Connect using the downward arrows icon to the right of the characteristic.
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
BLECharacteristic *characteristic;
bool clientConnected = false;
unsigned long lastSend = 0;
int counter = 0;
class ServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer *server) {
clientConnected = true;
}
void onDisconnect(BLEServer *server) {
clientConnected = false;
BLEDevice::startAdvertising();
}
};
void setup() {
Serial.begin(115200);
BLEDevice::init("ESP32-Sensor");
BLEServer *server = BLEDevice::createServer();
server->setCallbacks(new ServerCallbacks());
BLEService *service = server->createService(SERVICE_UUID);
characteristic = service->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY
);
characteristic->addDescriptor(new BLE2902()); // Required for notifications
service->start();
BLEAdvertising *advertising = BLEDevice::getAdvertising();
advertising->addServiceUUID(SERVICE_UUID);
BLEDevice::startAdvertising();
}
void loop() {
// Send a notification every 2 seconds without delay()
if (clientConnected && millis() - lastSend >= 2000) {
lastSend = millis();
counter++;
String text = String(counter);
characteristic->setValue(text);
characteristic->notify();
Serial.print("Notification sent: ");
Serial.println(text);
}
}Here, the counter acts as a simulated sensor reading. In a real project, you could replace it with the temperature measured through an analog pin. Usingmillis()avoids blocking the program withdelay(), as explained in the lesson on interrupts. Notifications are more energy-efficient than having the smartphone repeatedly request a value: the client no longer needs to poll the server continuously, helping both devices save power.
Small Messages Only
By default, a BLE notification can carry approximately20 bytes of data. This is more than enough for a temperature reading or a counter, but not for sending long text or images. BLE is designed for frequent, small messages, not large data transfers.
The UUIDs in these examples come from official sample code and are suitable for learning. For your own services, generate unique UUIDs using an online generator (search for "UUID generator") to avoid conflicts with nearby BLE devices.
A 128-bit UUID consists of 32 hexadecimal digits divided into five groups separated by hyphens (8-4-4-4-12). BLE also supports short 16-bit UUIDs, reserved for standardized services, such as the Battery Service or Heart Rate Service. For your own custom services, always use full 128-bit UUIDs.
BLE is a good choice when your project runs on a battery, when no Wi-Fi network is available nearby, or when you simply want to control the board from a smartphone a few meters away. Wi-Fi is preferable when data must reach the Internet or when large amounts of data need to be transferred. Combined with the deep sleep mode covered earlier, BLE makes it possible to build sensors that can run for a long time on a small battery.
Good to Know
Using Wi-Fi and Bluetooth simultaneously on the ESP32 is possible, but they share the same antenna and use a significant amount of memory. Performance may decrease, and the program becomes larger. Choose only one of the two technologies when possible.
No Security by Default
In these examples, any nearby smartphone can connect to the ESP32 and write to its characteristics: there is no pairing or password protection. This is acceptable for a simple LED learning exercise, but never use such a setup to control sensitive or dangerous equipment without adding appropriate security.
service->start()orBLEDevice::startAdvertising(): the device may be invisible or have no active service.PROPERTY_WRITEproperty: the smartphone cannot write to the characteristic.Exercise
2(the LED blinks) and3(the LED is set to half brightness using PWM). Test each command from nRF Connect. To make the LED blink without blocking the board, usemillis()instead ofdelay().Go Further
PROPERTY_NOTIFYandPROPERTY_READproperties of a BLE characteristic, then explain why notifications are useful for a sensor that sends regular measurements. Next, connect a potentiometer and send its value as a percentage to the smartphone through a notification every second.