Lesson 11 / 11100%

Lesson 11

Bluetooth Low Energy

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 ESP32's Two Bluetooth Technologies

The classic ESP32 supports two distinct Bluetooth technologies:

  • Bluetooth Classic: designed for continuous data or audio transmission (headphones, speakers). It can simulate a wireless serial connection.
  • Bluetooth Low Energy (BLE): designed to exchange small amounts of data while consuming very little energy (sensors, smartwatches, beacons). It is widely used today and is the only Bluetooth technology supported by the ESP32-C3, S3, and C6 chips.

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 Terminology

BLE communication follows a specific structure, which can be compared to a restaurant:

  • The server (or peripheral): the device providing data, here the ESP32. It advertises its presence so nearby devices can discover it.
  • The client (or central): the device connecting to the server, typically a smartphone.
  • A service: a group of related data, like a section of a restaurant menu.
  • A characteristic: a specific piece of data within a service that the client can read, write, or receive through notifications, like an item on the menu.
  • A UUID: a long, unique identifier assigned to each service and characteristic.
Diagram: a smartphone (client) connected to an ESP32 (server) containing one service with two characteristics, each identified by a UUID.

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.

What a Characteristic Can Do

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.

Preparing Your Smartphone

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.

A BLE Server That Controls an LED

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.

ble_led.ino
#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.

Testing with nRF Connect

  • In the "Scanner" tab, find the device namedESP32-Courseand tap "Connect".
  • Open the service whose UUID begins with "4fafc201".
  • For the characteristic beginning with "beb5483e", tap the write icon (upward arrow), choose the text format (UTF-8), and send "1", then "0".
  • Observe the board's LED and the messages displayed in the Serial Monitor.
Screenshot: the nRF Connect application showing the ESP32-Course device in the scanner list, followed by writing the value 1 to the characteristic.

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.

If the Device Does Not Appear in the Scanner

This is the most common problem during a first test. Check the following points in order:

  • Open the Serial Monitor and verify that the "BLE started" message appears. Otherwise, the program may not have started correctly.
  • On Android, make sure the application has the required Bluetooth and location permissions.
  • Move the smartphone closer to the board and scan again. BLE range can be limited to a few meters, or around ten meters in an open area.
  • Press the board's reset button, then start another scan.
  • Check that your board supports Bluetooth. The ESP32-S2 does not.

Detecting Connections and Disconnections

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.

ble_connection.ino
#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);
}

Sending Sensor Readings with Notifications

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.

ble_notification.ino
#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.

Generating Your Own UUIDs

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.

Wi-Fi or Bluetooth: Which Should You Choose?

  • Wi-Fi: longer range, Internet access, and higher data transfer rates, but greater power consumption.
  • BLE: very low power consumption and direct communication with a smartphone without using a router, but more limited range and data transfer speed.

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.

Common Mistakes

  • Forgettingservice->start()orBLEDevice::startAdvertising(): the device may be invisible or have no active service.
  • Using a board without Bluetooth support, such as the ESP32-S2.
  • Writing a value in nRF Connect using the wrong format (for example, hexadecimal instead of text): the received character will not be "1" or "0".
  • Forgetting to restart advertising after disconnection: the device becomes undiscoverable until it restarts.
  • Forgetting thePROPERTY_WRITEproperty: the smartphone cannot write to the characteristic.
  • Copying code written for another version of the esp32 board package without checking compatibility.

Key Takeaways

  • BLE is a low-power Bluetooth technology suitable for exchanging small amounts of data. It is not directly compatible with Bluetooth Classic.
  • A BLE server exposes services containing characteristics, each identified by a UUID.
  • A characteristic can be read, written, or sent through notifications, depending on its properties.
  • Callbacks allow the program to respond to a write operation, a connection, or a disconnection.
  • Advertising must be restarted after disconnection so the device remains discoverable.
  • nRF Connect allows you to test a BLE project without developing a smartphone application.

Exercise

Modify the program so that the characteristic also accepts the characters2(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

Research the difference between thePROPERTY_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.