Try Embedded

Bluetooth Low Energy

Advertising, GAP roles, GATT, connection parameters and pairing.

Bluetooth, redesigned for coin cells

Bluetooth Low Energy (BLE, Bluetooth Smart) arrived with Bluetooth 4.0 and is a different protocol from Classic Bluetooth (BR/EDR), sharing only the 2.4 GHz band and the brand.

Classic BluetoothBluetooth Low Energy
Designed forContinuous streams: audio, serial cablesShort bursts of small data
PowerTens of mA while connectedAverage µA; peaks of a few mA
Connection set-upSecondsMilliseconds
Typical usesHeadphones (A2DP), car kits, older serial modulesWearables, sensors, beacons, phone accessories, medical devices
AudioYesLE Audio (Bluetooth 5.2+, LC3 codec)

Every phone supports BLE, which is its biggest advantage: no hub, no app store needed for some uses (Web Bluetooth), and a user interface for free.

Roles: GAP

The Generic Access Profile (GAP) defines how devices find and connect to each other:

RoleDoesExample
BroadcasterAdvertises only, never connectsBeacon
ObserverScans onlyBeacon receiver
PeripheralAdvertises and accepts connectionsHeart-rate strap, sensor
CentralScans and initiates connectionsPhone, gateway

Advertising

A peripheral broadcasts small advertising packets on three channels (37, 38, 39), chosen to avoid the busiest Wi-Fi channels, at an advertising interval between 20 ms and 10.24 s. Legacy advertising payloads hold 31 bytes, made of length-type-value structures:

#include <stdio.h>
#include <stdint.h>

int main(void) {
  /* A legacy advertising payload: flags, a 16-bit service UUID, and a short name. */
  const uint8_t adv[] = {
    0x02, 0x01, 0x06,                   /* flags: LE General Discoverable, BR/EDR not supported */
    0x03, 0x03, 0x0D, 0x18,             /* complete list of 16-bit UUIDs: 0x180D (Heart Rate) */
    0x06, 0x09, 'P', 'u', 'l', 's', 'e' /* complete local name */
  };
  printf("payload %u of 31 bytes used\n", (unsigned)sizeof adv);
  for (unsigned i = 0; i < sizeof adv; i += adv[i] + 1) {
    uint8_t len = adv[i], type = adv[i + 1];
    printf("AD type 0x%02X, %u data byte(s)", type, len - 1);
    if (type == 0x03) printf(": UUID 0x%04X", adv[i + 2] | (adv[i + 3] << 8));
    if (type == 0x09) printf(": name \"%.*s\"", len - 1, (const char *)&adv[i + 2]);
    printf("\n");
  }
  return 0;
}

A scanner can request a scan response for another 31 bytes. Bluetooth 5 extended advertising allows up to 255 bytes per packet (chained up to about 1650) on secondary channels.

Beacons (iBeacon, Eddystone) are just peripherals that only advertise, with a standard payload layout.

Connections

After a central connects, the two devices hop across 37 data channels in step, exchanging packets at connection events. Three parameters, negotiated with the central (the phone usually has the final say), set power and latency:

ParameterRangeEffect
Connection interval7.5 ms to 4 sHow often the devices meet. Shorter: lower latency, more power
Peripheral latency (slave latency)0 to ~500 eventsHow many events the peripheral may skip when it has nothing to send
Supervision timeout100 ms to 32 sHow long without a packet before the link is declared lost

A sensor might use a 1 s interval with latency 4 to send occasionally while staying responsive. iOS and Android impose their own limits on acceptable values; request parameters within them.

GATT: the data model

Once connected, data is organised by the Generic Attribute Profile (GATT):

Profile
 └── Service (e.g. Heart Rate, UUID 0x180D)
      ├── Characteristic: Heart Rate Measurement (0x2A37)   properties: Notify
      │    └── Descriptor: CCCD (0x2902)  ← client writes here to enable notifications
      └── Characteristic: Body Sensor Location (0x2A38)     properties: Read
  • A service groups related characteristics. Standard ones (Heart Rate, Battery 0x180F, Device Information 0x180A) use 16-bit UUIDs assigned by the Bluetooth SIG; custom ones use random 128-bit UUIDs.
  • A characteristic is a value with properties: Read, Write, Write Without Response, Notify, Indicate.
  • The peripheral is usually the GATT server (holds the data); the phone is the client.

Ways data moves:

OperationDirectionAcknowledgedUse
ReadClient pullsYesOccasional values
Write / Write Without ResponseClient pushesYes / noCommands, configuration
NotificationServer pushesNoStreaming sensor data
IndicationServer pushesYes (slower)Important events

Notifications only flow after the client writes 0x0001 to the characteristic's CCCD.

Throughput

Data per packet is limited by the ATT MTU (default 23 bytes, so 20 bytes of payload; negotiable to 247 or more), packets per connection event, the connection interval, and the PHY (1M, 2M, or Coded for long range at 125 or 500 kbit/s). Practical throughput ranges from a few kB/s with defaults to over 100 kB/s with 2M PHY, large MTU and data length extension.

Security

BLE pairing establishes keys; bonding stores them for later reconnections.

Pairing methodProtection against eavesdroppingAgainst man-in-the-middle
Just WorksYes (LE Secure Connections)No
Passkey entryYesYes
Numeric comparisonYesYes
Out of band (NFC)YesYes

Use LE Secure Connections (Bluetooth 4.2+, ECDH-based); legacy pairing is weak. Protect characteristics with permission levels (encryption or authenticated encryption required). Devices can use resolvable private addresses that change periodically, so they cannot be tracked.

On the device

BLE stacks come with the SoC: Nordic's SoftDevice or Zephyr's Bluetooth stack on nRF, NimBLE (Apache Mynewt, used on ESP32), Silicon Labs, TI, STM32WB. The radio has strict timing; the stack usually runs at the highest interrupt priority, and application code must not block it.

Pitfall: Phones cache GATT tables. After a firmware update that changes services, a bonded phone may keep using the old table until Bluetooth is toggled. Implement the Service Changed characteristic (and a database hash) so phones refresh.

Interview question: How do connection parameters affect a BLE peripheral's power and latency?

Answer: The connection interval sets how often the devices wake to exchange packets: short intervals give low latency and higher throughput but more radio-on time; long intervals save power. Peripheral latency lets the peripheral skip connection events when it has nothing to send, saving power while still being able to send at the next event without renegotiation. The supervision timeout determines how quickly a lost link is detected and must exceed the interval times (1 + latency). The central decides, so the peripheral requests values within what phones accept.

Interview question: Describe the GATT hierarchy and how a sensor value reaches a phone.

Answer: A GATT server exposes services, each a collection of characteristics; each characteristic has a value, properties (read, write, notify, indicate) and descriptors such as the CCCD. The phone, as GATT client, discovers services and characteristics after connecting, reads values or enables notifications by writing to the CCCD. The sensor then pushes new values as notifications at connection events, limited per packet by the negotiated ATT MTU.

Build it: advertise the container's status

This is step 2 of the module project, the shipping-container tracker tag. In the yard, staff walk past rows of containers with a phone app, and the tag tells them its status without anyone connecting: everything goes in its advertising packet, which holds at most 31 bytes. A few bytes too many and the stack refuses the whole packet; a name cut in the wrong way and the app shows rubbish.

Lab: Build the 31-byte advertising packet

Advertising data is a list of AD structures, each a length byte (counting the type byte and the data), a type byte, then the data. adv_build(out, s, name) writes, in this order, and returns the total length:

  1. Flags (type 0x01): one byte, 0x06 (general discoverable, no classic Bluetooth).
  2. Manufacturer data (type 0xFF): the company identifier 0xFFFF (the one reserved for testing), then the container number (4 bytes), the battery percentage, the temperature in °C (signed), and a status byte with bit 0 set when the door has been opened and bit 1 after a shock. Bluetooth numbers are little-endian.
  3. The name, in whatever room is left of the 31 bytes: as a complete local name (type 0x09) if it all fits, otherwise as a shortened local name (type 0x08) holding as many leading characters as fit. Leave the name out if it is empty or not even one character fits.

adv_units(ms) converts an advertising interval to the controller's units of 0.625 ms, rounding down, and clamps it to the allowed range of 20 ms to 10.24 s (32 to 16384 units). The tag advertises every 100 ms for a minute after an event, then every 2 s.

Going deeper

Interview question: How would you design a fitness band's Bluetooth link to last a week on a charge?

Answer: Use standard GATT services where they exist (Heart Rate, Battery) so any app works, advertise slowly when nobody is connected, negotiate a long connection interval and slave latency once connected, batch data and send it in few packets, and keep the radio off between. Measure the current profile with a power analyser and budget each activity.

Interview question: What changed in Bluetooth 5 that matters for embedded devices?

Answer: The 2M PHY doubles the on-air data rate for faster transfers and lower energy per byte; the Coded PHY (125 and 500 kbit/s) adds forward error correction for up to about four times the range; extended advertising allows much larger advertising payloads on secondary channels and periodic advertising for broadcasting to many receivers. Later versions added direction finding (5.1), LE Audio and isochronous channels (5.2), and more.

Interview question: How does a peripheral achieve low power while connected?

Answer: By negotiating a long connection interval and peripheral latency so it only wakes when it has data, sending data in few, full packets (large MTU, data length extension, 2M PHY), using notifications rather than polled reads, and keeping advertising intervals long when disconnected. Between connection events the radio is off and the MCU sleeps, so average currents of a few microamps are possible.

Explain it: In your own words, explain how a sensor value gets from a BLE peripheral to a phone app.

Answer: The peripheral advertises so the phone can find it, and the phone's app connects as the central. The app then discovers the peripheral's GATT services and characteristics, the data model in which each value is a characteristic with properties such as read or notify. To receive updates, the app writes to the characteristic's configuration descriptor to enable notifications. From then on, whenever the sensor has a new value, the peripheral sends it as a notification at the next connection event, and the app's callback receives it.