Module 6 - Bluetooth & BLE

6.1 Introduction to Bluetooth Technology

What is Bluetooth?

Bluetooth is a global wireless technology standard for exchanging data over short distances. Its primary purpose is to replace the cables connecting electronic devices, allowing for communication in a clean, efficient manner. It operates in the unlicensed Industrial, Scientific, and Medical (ISM) radio frequency band, specifically from 2.402 GHz to 2.480 GHz.

At its core, Bluetooth facilitates the creation of Wireless Personal Area Networks (WPANs). This means it connects devices that are in close proximity to a user, such as a smartphone, wireless headphones, a smartwatch, a keyboard, and a laptop, allowing them to work together seamlessly.

All Bluetooth devices are certified and managed by the Bluetooth Special Interest Group (SIG), a non-profit organization that oversees the development of the standards, manages the licensing of the technology, and ensures that devices from different manufacturers can interoperate correctly.

The Origin of the Name and Technology

The name "Bluetooth" is an homage to a 10th-century Viking king, Harald "Bluetooth" Gormsson. King Harald was famous for uniting the disparate tribes of Denmark and Norway into a single kingdom. Similarly, the creators of the technology saw it as a way to unite different communication protocols from various devices into one universal standard.

The iconic Bluetooth logo is a combination of two ancient Norse runes, which are the initials of Harald Bluetooth:

The technology itself was initiated in 1989 at Ericsson Mobile in Sweden. The goal was to develop a low-power, low-cost radio interface for wireless headsets. In 1998, Ericsson, along with Intel, Nokia, and Toshiba, formed the Bluetooth Special Interest Group (SIG) to establish a single, open standard, which has since grown to include tens of thousands of member companies.

6.2 Core Specifications and Evolution

Bluetooth technology is not static; it has evolved through numerous versions, each adding new capabilities, increasing speed, and reducing power consumption.

Bluetooth 1.0 (1999):

Bluetooth 1.2 (2003):

Bluetooth 2.0 + EDR (2004):

Bluetooth 2.1 + EDR (2007):

Bluetooth 3.0 + HS (2009):

Bluetooth 4.0 (2010): The Birth of BLE

Bluetooth 4.1 (2013):

Bluetooth 4.2 (2014):

Bluetooth 5.0 (2016): A Major Leap for BLE

Bluetooth 5.1 (2019):

Bluetooth 5.2 (2020):

Bluetooth 5.3 (2021):

Bluetooth 5.4 (2023):

6.3 Core Technology Architectures

Modern Bluetooth is not a single technology but a combination of three distinct architectures designed for different use cases. A device can implement one or more of these.

Bluetooth Classic (BR/EDR)

This is the original Bluetooth protocol, designed for continuous, point-to-point data streaming.

Bluetooth Low Energy (BLE)

BLE was introduced in Bluetooth 4.0 and is the dominant technology for the Internet of Things.

Bluetooth Mesh

Bluetooth Mesh is not a separate radio technology; it's a networking protocol that operates on top of the BLE radio.

Key Differences: A Summary

Feature Bluetooth Classic (BR/EDR) Bluetooth Low Energy (BLE) Bluetooth Mesh
Primary Use Case Audio Streaming, File Transfer IoT Sensors, Wearables, Beacons Large-Scale Control Networks
Throughput Medium-High (~2.1 Mbps) Low-Medium (~1-2 Mbps) Low
Power Consumption Medium Very Low Low (node-dependent)
Topology Piconet (Master-Slave) Star (Central-Peripheral) Mesh (Node-to-Node)
Connection Time Slower (~100ms) Very Fast (<3ms) N/A (Always on or advertising)
Number of Devices 1 Master to 7 Slaves 1 Central to Many Peripherals Thousands of Nodes in a Network
Example Wireless Headphones Heart Rate Monitor Smart Building Lighting

6.4 Bluetooth Audio: From Classic to Auracast™ (Optional)

Legacy Audio (Classic Profiles)

For over two decades, Bluetooth audio has been powered by profiles running on the Bluetooth Classic radio. These profiles are the foundation of the wireless audio market.

While functional, this legacy audio architecture has limitations: it is relatively power-hungry, the SBC codec is inefficient, and it cannot natively support use cases like True Wireless Stereo earbuds without vendor-specific workarounds.

Introduction to LE Audio

Introduced in the Bluetooth 5.2 specification, LE Audio is the next generation of wireless sound, designed to address the limitations of Classic Audio. It is a completely new architecture that operates exclusively on the power-efficient Bluetooth Low Energy (BLE) radio.

LE Audio brings significant benefits:

The LC3 Codec (Low Complexity Communications Codec)

The cornerstone of LE Audio is the LC3 codec. It is the new mandatory codec for all LE Audio devices, representing a massive leap in efficiency and flexibility over the classic SBC codec.

The primary advantage of LC3 is its ability to provide high-quality audio at much lower data rates. This gives developers a choice:

  1. Deliver Higher Quality: At the same data rate as SBC, LC3 provides a significant and noticeable improvement in audio fidelity.

  2. Extend Battery Life: LC3 can provide the same or slightly better audio quality as SBC but at roughly half the data rate. A lower data rate means the radio is active for less time, drastically reducing power consumption.

This efficiency makes LC3 a superior technology for all wireless audio applications, from high-fidelity headphones to power-constrained hearing aids.

Auracast™ Broadcast Audio

Auracast™ is a revolutionary new capability built on LE Audio that enables a single source device to broadcast audio to an unlimited number of nearby receivers. Think of it as public Wi-Fi, but for audio.

How It Works:

  1. An Auracast™ transmitter (e.g., a TV in an airport, a laptop in a lecture hall) broadcasts its audio stream.

  2. Listeners with Auracast™ assistants (e.g., smartphones or smartwatches) can scan for these broadcasts in the area.

  3. The assistant presents a list of available Auracast™ streams to the user, who can then select one to join.

  4. The audio is then routed to the user's Auracast™ receiver (e.g., earbuds, headphones, or hearing aids).

Key Use Cases:

6.5 High-Accuracy Location Services (Optional)

Proximity Solutions (Beacons & RSSI)

The simplest form of Bluetooth location services is based on proximity. This is typically implemented using beacons, which are small BLE devices that continuously broadcast advertising packets.

A receiver, such as a smartphone, can listen for these packets and measure the Received Signal Strength Indicator (RSSI). RSSI provides a rough estimate of the distance between the receiver and the beacon—a stronger signal generally means a closer device.

This method is useful for applications like:

However, RSSI is not very accurate. The signal strength can be affected by obstacles (walls, people), device orientation, and environmental interference, making it unsuitable for applications that require precise location data.

Direction Finding (AoA & AoD)

Introduced in Bluetooth 5.1, Direction Finding provides a way to determine the precise direction of a Bluetooth signal, enabling Real-Time Location Systems (RTLS) with sub-meter accuracy. It uses two distinct methods:

This technology is the foundation for a new class of high-precision services, including indoor navigation, industrial asset tracking, and secure digital key access.

6.6 Bluetooth and the Internet of Things (IoT)

Bluetooth Mesh Networking in Detail

Bluetooth Mesh is a software-based networking solution that runs on top of the BLE physical radio. It is designed to support large-scale, many-to-many device communication, making it ideal for smart buildings and industrial IoT.

Key concepts of a Mesh network include:

The architecture is highly reliable because there is no single point of failure; if one node goes down, messages can automatically find an alternative path through other nodes.

Periodic Advertising with Responses (PAwR)

Introduced in Bluetooth 5.4, Periodic Advertising with Responses (PAwR) is a new communication mode designed for large-scale, one-to-many IoT applications that require low-power, bidirectional communication without forming a connection.

How It Works:
A central device (a broadcaster) sends out small, time-synchronized advertising packets on a predictable schedule. The thousands of listening devices (observers) are synchronized to this schedule and only wake up for a brief moment to listen for a relevant packet. This saves an enormous amount of power.

Crucially, after each broadcast event, there are dedicated time slots where the observers can send back a small response. This enables bidirectional communication for acknowledgements, sensor data, or status updates.

Use Case: Electronic Shelf Labels (ESL)

The primary and first officially adopted profile for PAwR is Electronic Shelf Labels (ESL). In a retail environment, a single gateway can control and update prices on tens of thousands of e-paper labels throughout the store.

6.7 Bluetooth Security

Legacy Pairing vs. LE Secure Connections

Pairing is the process of creating a trusted relationship between two devices by generating and storing shared secret keys.

Encryption, Privacy, and MITM Protection

Modern Bluetooth security is built on three core pillars:

  1. Encryption (Confidentiality): Once devices are paired, the connection can be encrypted. Bluetooth uses the AES-CCM algorithm to encrypt all data sent over the link. This ensures that if an attacker were to listen to the radio traffic, they would only see unintelligible encrypted data, not the actual information.

  2. Privacy (Anti-Tracking): To prevent malicious actors from tracking a user by listening for their device's Bluetooth address, BLE uses Resolvable Private Addresses (RPAs). A device with this feature enabled will periodically change its public Bluetooth address to a new, randomized one. Only devices that have previously paired with it possess the key (the IRK - Identity Resolving Key) needed to resolve this random address and identify the device.

  3. Authentication and MITM Protection: A Man-in-the-Middle (MITM) attack occurs when an attacker secretly sits between two devices and relays their communication, potentially altering it. LE Secure Connections protects against this by authenticating the connection during pairing. This is done using one of several association models:

    • Passkey Entry: The user enters a 6-digit number on both devices.

    • Numeric Comparison: A 6-digit number is displayed on both devices, and the user confirms they are the same. This is the most common method for devices with displays.

    • If a connection is authenticated, the devices have proven they are communicating directly with each other and not an imposter.

Security Best Practices for Developers

For students building Bluetooth applications, security should be a primary concern.

6.8 The Bluetooth Protocol Stack

The Bluetooth protocol stack is a software framework that defines how Bluetooth devices communicate. It is structured in layers, where each layer provides services to the layer above it and uses services from the layer below it. The stack is divided into two main components: the Controller and the Host.

The Controller

The Controller is responsible for the low-level radio operations. It handles the transmission and reception of radio signals and manages the physical connection between devices. It is often implemented as a dedicated chip (a "System-on-a-Chip" or SoC) that includes the radio hardware.

The Host

The Host is responsible for the high-level logic, data organization, and application functionality. It typically runs on the main processor of a device (e.g., in your ESP32 code).

6.9 Practical Implementation with ESP32

This chapter provides a hands-on project to demonstrate the core concepts of a BLE peripheral device using an ESP32. We will move beyond a simple serial example and create a simulated BLE Heart Rate Sensor. This is a standard profile that teaches the essential concepts of services, characteristics, and notifications.

Project: Create a BLE Heart Rate Sensor

Goal: Configure the ESP32 to act as a BLE peripheral that advertises the standard Heart Rate service. When a central device (like a smartphone) connects and enables notifications, the ESP32 will periodically send a simulated heart rate measurement.

You Will Need:

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

// Standard Bluetooth Service and Characteristic UUIDs for Heart Rate
#define SERVICE_UUID        "0000180d-0000-1000-8000-00805f9b34fb" // Heart Rate Service
#define CHARACTERISTIC_UUID "00002a37-0000-1000-8000-00805f9b34fb" // Heart Rate Measurement

BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;

// This class handles server events like client connect/disconnect
class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
      Serial.println("Client Connected");
    }

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
      Serial.println("Client Disconnected");
    }
};

void setup() {
  Serial.begin(115200);
  Serial.println("Starting BLE Heart Rate Sensor...");

  // 1. Initialize the BLE device and set its name
  BLEDevice::init("ESP32 Heart Rate Sensor");

  // 2. Create the BLE Server
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks()); // Set the event handler

  // 3. Create the BLE Service using the standard Heart Rate UUID
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // 4. Create a BLE Characteristic for the Heart Rate Measurement
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID,
                      BLECharacteristic::PROPERTY_READ |
                      BLECharacteristic::PROPERTY_NOTIFY
                    );

  // 5. Add a 2902 descriptor to the characteristic. This is ESSENTIAL
  // for the client to be able to enable notifications.
  pCharacteristic->addDescriptor(new BLE2902());

  // 6. Start the service
  pService->start();

  // 7. Start advertising, so other BLE devices can find this one
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID); // Advertise our service
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(0x06);
  pAdvertising->setMinPreferred(0x12);
  BLEDevice::startAdvertising();
  
  Serial.println("Characteristic defined! Now you can scan for 'ESP32 Heart Rate Sensor' on your phone.");
}

void loop() {
  // Check if a client is connected
  if (deviceConnected) {
    // Generate a simulated heart rate value
    // The first byte is a flag (0), the second is the 8-bit heart rate value
    static uint8_t heartRate = 60;
    heartRate++;
    if (heartRate > 100) {
      heartRate = 60; // Reset after 100
    }
    
    uint8_t heartRateData[2] = {0, heartRate};
    
    // Set the characteristic's new value
    pCharacteristic->setValue(heartRateData, 2);
    
    // Send a notification to the connected client
    pCharacteristic->notify();
    
    Serial.print("Heart Rate Notification Sent: ");
    Serial.println(heartRate);
  }
  delay(1000);
}

Code Walkthrough

  1. Initialization: We initialize the BLE stack using BLEDevice::init() and give our device a public name.

  2. Server and Service: We create a BLEServer to manage connections and a BLEService to hold our data. We use the official UUID for the "Heart Rate Service."

  3. Characteristic: Inside the service, we create a BLECharacteristic for the "Heart Rate Measurement." We set its properties to allow a client to both READ the value and subscribe to NOTIFY (notifications).

  4. Descriptor (BLE2902): This is a critical step. The BLE2902 descriptor is the Client Characteristic Configuration Descriptor (CCCD). A client (your phone) writes to this descriptor to tell the server (the ESP32) that it wants to receive notifications. Without this, notifications will not work.

  5. Advertising: We start advertising and include the Service UUID. This tells scanning devices what services we offer before they even connect.

  6. The Loop: In the main loop, we check if a client is connected. If so, we generate a new simulated heart rate value, update the characteristic with setValue(), and then send it to the client using notify().

How to Test It

  1. Upload the code to your ESP32.

  2. Open the Arduino Serial Monitor to see the status messages.

  3. On your smartphone, open a BLE scanner app (like nRF Connect for Mobile).

  4. Scan for devices. You should see "ESP32 Heart Rate Sensor" in the list.

  5. Connect to the device. In the Serial Monitor, you should see "Client Connected."

  6. Find the Heart Rate Service and expand it to see the Heart Rate Measurement characteristic.

  7. Tap the "subscribe" or "enable notifications" icon (often a single or triple downward arrow).

  8. You should now see the value updating in your app every second, and the Serial Monitor will show the "Notification Sent" logs.

6.10 Real-World Applications and The Future

Modern Case Studies

Bluetooth is now a foundational technology in nearly every major tech domain:

The Future of Bluetooth

The evolution of Bluetooth is ongoing, driven by the needs of emerging markets. Key areas of future development include: