Bluetooth LE from Radio to GATT

A Bluetooth LE ring sleeps almost all the time. It wakes for a few milliseconds each interval to swap packets with a phone. Change the interval, radio speed and packet size, and see data rate, current and wait.

Learn how a small device finds a phone, agrees a schedule, and moves bytes through a table of attributes, and what each choice costs in battery.

Pick a radio speed and a packet size, then drag the connection interval. Watch how many packets fit in one event, how fast data moves, and how much current the quiet link burns. Then we build, piece by piece, the radio, the advertising, the connection, the table of data and the budget underneath.

You need to know what a byte and a packet are and a little C. We build the radio, the schedule and the data model from zero.

Part of Firmware from Zero to Expertise, the Bluetooth and wearables track. Built from the Nordic Developer Academy course Bluetooth LE Fundamentals, the Zephyr Bluetooth sources, the nRF52840 product specification and the Memfault Interrupt BLE throughput primer. Needs Buses on the Wire and the BLE chapter of Hardware Interfacing. Every idea is re-taught here in our own words and devices.

Tune a connection

30 ms

A model, not a measurement. Packet times follow the Bluetooth packet format (as coded in the Zephyr controller) with an encrypted link and 251-byte data length. Currents are the nRF52840 datasheet values: 6.40 mA transmit at 0 dBm and 6.26 mA receive, both at 1 Mbps and used for every speed here, and 3.16 µA asleep with the timer running. The 0.5 ms per event for waking and starting the clock is illustrative. Streaming means the device always has data waiting.

Chapter 0

A Radio That Sleeps

See why a battery device cannot keep its radio on, and how two devices agree to meet instead

Picture a smart ring. It sits on a finger, it is smaller than a thumbnail, and it carries a battery about the size of a shirt button. Once each second it must tell a phone your heart rate. The owner expects to charge it once a week, or never.

Here is the problem. A radio that is switched on draws current. For the Nordic nRF52840, a Bluetooth chip the lesson uses as its example, the datasheet gives 6.26 mA to listen and 6.40 mA to transmit at 0 dBm. A small battery of 220 mAh (an illustrative size) would run a radio that never sleeps for about 35 hours. A day and a half.

The same chip, asleep with its timer running, draws 3.16 µA. That is about 2,000 times less. The whole design of Bluetooth Low Energy (BLE, the short-range radio standard built for small batteries) follows from that one gap. Keep the radio off nearly all the time.

The trick: an appointment

A radio that is asleep cannot hear anyone. So the two sides must agree, in advance, on the exact moments they will both be awake. Think of two people who each work in a quiet office. They do not stay on the phone all day. They fix a call at ten past every hour, and they work in silence between calls.

BLE does exactly this. The agreed moment is a connection event. The gap between two events is the connection interval. In the event, the two devices swap a few packets in a few milliseconds and go back to sleep. Everything else in this lesson is a detail of how they find each other, agree the appointments, and use the minutes of each call well.

Play with the idea before we name more parts. Drag the interval and watch the same one second of life for the ring.

One second of a quiet link

Each tick is one connection event on a one second axis. The link carries no data, only empty packets that keep the clocks in step. Drag the interval and compare the ticks with the current bar.

100 ms

A model. Each event is an empty packet from the phone, a 150 µs gap, and an empty packet back, on the 1M radio, plus an illustrative 0.5 ms to wake up and start the clock. Currents are the nRF52840 datasheet values (6.26 mA receive, 6.40 mA transmit, 3.16 µA asleep). The battery is an illustrative 220 mAh and ignores the CPU and the sensor.

The ticks get sparse fast. At 1 s intervals the radio is awake for about three hundredths of one percent of the time, and the quiet link costs about 8 µA. At 7.5 ms it wakes 133 times a second and the cost is about 80 times higher. You pay for every appointment, even an empty one.

The three acts

Every BLE link goes through the same three acts, and this lesson walks them in order.

  1. Advertise. The ring is asleep and unknown. Now and then it shouts a short message, "I am here, and this is what I can do", on three fixed radio channels. The phone listens for it.
  2. Connect. The phone answers with a connection request that carries the appointment schedule. From then on, the two meet at every connection event.
  3. Exchange. Inside the events, the devices move data. They organise it as a table of named values called GATT, which is how a phone app reads "heart rate" without knowing anything about the ring's wiring.

Underneath all three sits the radio itself, with its own channels, speeds and packet format. So the chapters run from the bottom of the stack to the top: the radio, advertising, the connection, the three connection knobs, the table of data, packet size, throughput, and finally the energy bill.

Who is who

Two pairs of names will confuse you if they arrive late, so meet them now. At the radio level, the device that starts a connection is the central and the one that advertises is the peripheral. These roles belong to GAP, the Generic Access Profile, which covers how devices find and connect to each other.

At the data level, the device that holds the table of values is the GATT server and the one that reads it is the GATT client. The usual pairing is a phone as central and client, and a ring as peripheral and server. But the two pairs are separate ideas, and Chapters 3 and 5 pull them apart.

The road

  1. The radio and its packets: 40 channels, three speeds, and what one packet costs in microseconds.
  2. Advertising: how a sleeping device announces itself, and what fits in 31 bytes.
  3. Connecting: the request, the roles, the connection event and channel hopping.
  4. Interval, latency and timeout: the three knobs that trade power against delay.
  5. GATT: services, characteristics, the attribute table and the five operations.
  6. MTU and data length: how big one packet may be, and who splits what.
  7. Throughput: how many bytes a second the link really moves, and why.
  8. The energy bill: charge per event, per byte, and days on a battery.
  9. On real silicon: the Zephyr calls, and three symptoms to diagnose.
  10. Field guide: numbers, checklist, core code, and where to go next.
A BLE link carries no data. Why does the device still wake at every connection event?

Chapter 1

The Radio and Its Packets

Count the channels, pick a speed, and add up the microseconds that one packet spends on the air

Stand in a busy train station and try to talk to a friend across the hall. Everyone else is talking too. You need two things: a way to avoid the noisiest spots, and a way to tell your friend's voice from the crowd. A BLE radio needs the same two things, and the standard gives them as channels and addresses.

BLE lives in the 2.4 GHz band, a shared band that Wi-Fi and many other devices also use. The standard cuts the band into 40 channels, each 2 MHz apart. Nordic's course names the split: three advertising channels, numbered 37, 38 and 39, and 37 data channels, numbered 0 to 36.

The channel number is not the frequency. A chip is told a frequency offset above 2400 MHz. The Zephyr controller, the open source BLE stack the lesson reads, programs the nRF radio with 2 for channel 37, 26 for channel 38 and 80 for channel 39. So the advertising channels sit at 2402, 2426 and 2480 MHz. Data channel 0 sits at 2404 MHz and data channel 36 at 2478 MHz, with the advertising channels fitted between.

Three speeds: the PHY

The PHY (physical layer) is the way bits become radio waves. BLE has three common choices. LE 1M sends 1 million bits a second and is the default. LE 2M doubles the speed. LE Coded adds redundant bits so a weak signal still decodes. It comes in two strengths, S=2 at 500 kbps and S=8 at 125 kbps.

Nordic's advice is plain. Use 2M for faster transfers, with slightly shorter range. Use Coded when range matters more than speed. The speed of the radio is only the start of the story, because every packet carries a fixed cost on top of its data. We count that cost next.

Anatomy of one packet

A BLE data packet is a list of fields sent one after another. Each has a job.

Add the sizes and divide by the speed. For a full 251-byte payload on 1M with encryption: 1 + 4 + 2 + 251 + 4 + 3 = 265 bytes, which is 2,120 µs. The Zephyr source states the same limit as a constant, 2,120 µs for the largest data packet. On 2M the packet is 266 bytes at 2 bits per microsecond, which is 1,064 µs.

Now the empty packet that keeps a link alive. It has no payload and no MIC: 1 + 4 + 2 + 3 = 10 bytes, or 80 µs on 1M. That is the "ack" in every later timing. On Coded S=8 even this empty packet takes 720 µs, because the sync words and every bit are stretched eight times. The largest S=8 packet takes 17,040 µs, which is 17 ms.

Build a packet

The bar is one packet, with each field as wide as its time on the air. Choose a radio speed, then drag the payload size. Watch how much of the time is overhead.

27 bytes

Times follow the Zephyr controller's packet-time macros (subsys/bluetooth/controller/ll_sw/pdu.h). The link is assumed encrypted, so a MIC of 4 bytes is added when the payload is not empty. On the Coded PHY the preamble, access address, coding indicator and first terminator take 376 µs together, and the rest is stretched by 2 (S=2) or 8 (S=8).

The lesson is in the proportions. A 27-byte payload on 1M takes 328 µs, of which 112 µs is overhead. That is more than a quarter of the packet. A 251-byte payload spends only 5% on overhead. Big packets are cheaper per byte, a fact that returns in Chapters 6 and 7.

Hopping across the channels

A single noisy channel would ruin a fixed link. So a connection changes channel every event. The link layer follows a rule, the channel selection algorithm. In its first form, the Zephyr controller computes next = (last + hop) % 37. The hop increment is a number the phone chooses in the connection request. The standard allows 5 to 16.

Because 37 is prime, any hop visits all 37 channels before it repeats. If the next channel is marked unused in the channel map (a list of the channels the phone found clean), the link remaps it onto a good one. A lost packet is therefore retried on a different channel in the next event, as Nordic's course notes.

Hop the channels

Each square is a data channel, 0 to 36. The warm square is the channel of the current event. Step the events, change the hop increment, and mark a block of channels as noisy.

7

The rule is the Zephyr controller's first channel selection algorithm (lll_chan.c): unmapped = (last + hop) mod 37, and an unused result is remapped onto the list of used channels by its index. The noisy block is a toy; a real phone builds its channel map from measurements.

On real hardware. Take an nRF52840 DK and the nRF Sniffer for Bluetooth LE from Nordic's course (lesson 6). Capture a connection and look at the time stamps of consecutive packets. A full data packet and its empty reply should be separated by about the packet time plus 150 µs, which is what this chapter computes.

An empty packet on LE 1M has a 1 byte preamble, 4 byte access address, 2 byte header and 3 byte CRC. How long is it on the air?

Chapter 2

Advertising: Shouting Into the Dark

Follow a sleeping device as it announces itself on three channels, and fit its message into 31 bytes

The ring is in a drawer. Its owner opens the phone app and taps "Add device". The phone has no idea where the ring is, or whether it exists. The ring has no idea whether any phone is listening. Neither side can set up an appointment yet, because an appointment needs a conversation, and there is none.

BLE solves this with a lopsided habit. The ring advertises: at regular times it wakes, sends one short message, and sleeps again. The phone scans: it listens, one channel at a time, and collects every message it hears. Nordic's course names the two purposes of advertising. One is to broadcast data to neighbours. The other is to say "I am here, you may connect".

One advertising event

An advertising event sends the same packet once on each of the three advertising channels, 37, 38 and 39, in turn. A scanner can only listen on one channel at a time, so sending on all three raises the chance that one of them lands in its ear. After each packet, the ring listens for a short moment in case the phone wants to answer.

Between events the ring sleeps for the advertising interval. Nordic's course gives the range as 20 ms to 10.24 s in steps of 0.625 ms. It also adds a random delay of 0 to 10 ms before each event, so two rings with the same interval do not collide on every try. The Zephyr stack suggests defaults: 30 to 60 ms for a device the user is waiting for, 100 to 150 ms for the next tier, and 1 to 1.2 s for slow background advertising.

Short intervals make the ring easy to find and cost current. Long intervals save current and make the phone wait. This is the same trade as the connection interval, in a new place.

Advertise on three channels

The top three lanes are one advertising event, stretched so you can see it: a warm packet on each channel, then a blue window where the ring listens for an answer. Drag the interval and the message size.

100 ms
18 bytes

A model. Each packet is an ADV_IND on the 1M radio: preamble 1, access address 4, header 2, the 6 byte address, your data, CRC 3. After each packet the model listens 326 µs (150 µs gap plus a 22 byte scan request), an illustrative window. Currents are nRF52840 datasheet values; 0.5 ms of wake-up per event is illustrative. The wait is the interval plus the 10 ms maximum random delay.

Try 20 ms and then 10.24 s. The first costs several hundred microamps. The second costs close to the sleep floor and can leave the phone waiting ten seconds. Real products often advertise fast for the first 30 seconds after a button press, then slow down. The user is watching the screen during the fast phase.

What the message holds

The legacy advertising packet has a 2 byte header, a 6 byte advertiser address that names the sender, and up to 31 bytes of data. The 37 byte maximum is a constant in the Zephyr source. Those 31 bytes are all you get, so the format is tight.

The data is a list of AD structures. Each one has a length byte, a type byte and then the data. The length counts the type byte plus the data, not itself. Nordic lists the common types: Flags (one byte of switches), the complete local name the user sees when scanning, and manufacturer specific data, where a company puts its own bytes.

The type numbers come from the Bluetooth assigned numbers, which the Zephyr headers repeat: Flags is 0x01, the 16-bit service UUID list is 0x03, the complete name is 0x09 and manufacturer data is 0xFF. The flag value 0x06 means "general discoverable, and classic Bluetooth not supported" (0x02 plus 0x04).

c  (Zephyr)static const struct bt_data ad[] = {
    BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),  /* 02 01 06 */
    BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x0D, 0x18),                        /* 03 03 0D 18: Heart Rate service 0x180D */
    BT_DATA(BT_DATA_NAME_COMPLETE, "Ring-7F", 7),                       /* 08 09 52 69 6E 67 2D 37 46 */
};
bt_le_adv_start(BT_LE_ADV_CONN_FAST_1, ad, ARRAY_SIZE(ad), NULL, 0);   /* connectable, 30 to 60 ms */

That list is 3 + 4 + 9 = 16 bytes, so it fits with 15 to spare. The macros are real: BT_DATA_BYTES builds one AD structure, and BT_LE_ADV_CONN_FAST_1 is the Zephyr name for connectable advertising at the "fast mode 1" interval of 30 to 60 ms. Build your own below and watch the budget.

Fit the 31 bytes

Switch AD structures on. Each shows as bytes: length, type, data. If the total passes 31, move the name to the scan response, the second 31 bytes a scanner can ask for.

8 bytes

The type codes (0x01, 0x03, 0x09, 0xFF) and flag bits are from the Zephyr headers. The name "Ring-7F" is made up. The manufacturer data starts with a 2 byte company ID, shown here as the placeholder FF FF, then your bytes.

Connectable, scannable, and the scan response

Not every advertiser accepts a connection. A connectable advertiser (the usual ADV_IND) says "you may connect". A non-connectable one only broadcasts, like a beacon. A scannable advertiser also answers a scan request. Nordic describes the exchange: the scanner asks for more information, and the ring replies with a scan response on the same channel, with no connection needed. The scan response is another 31 bytes, so the first packet can carry the service and the second can carry the name.

The cost is a second packet, but only when a scanner asks. A beacon that wants the lowest power sends non-connectable, non-scannable packets and never listens, which also removes the listen window from the current in the device above.

On real hardware. Flash an advertising sample onto an nRF52840 DK, start nRF Sniffer, and read the interval between packets on one channel. It should match your setting plus a random 0 to 10 ms. Then change BT_LE_ADV_CONN_FAST_1 to a slow interval and measure the average current with a power profiler.

An advertiser sends one packet on each of channels 37, 38 and 39, then sleeps. What does lengthening the advertising interval from 100 ms to 1 s change?

Chapter 3

Connecting: Agreeing the Appointments

Watch a phone answer an advertisement, hand over a schedule, and keep the link alive through lost packets and drifting clocks

The user taps "Ring-7F" in the app. A moment ago the phone only heard an advertisement. Now it wants a private, scheduled conversation. What does it send, and to whom, and when?

First, the two roles. Nordic's course calls them central and peripheral. The central scans and starts the connection. The peripheral advertises and accepts. A phone is the usual central. A ring or a sensor is the usual peripheral. The roles belong to the link, not to the chip: some chips can be central on one link and peripheral on another.

The central sends a connection request in the moment right after it hears a connectable advertisement. That is the listen window you saw in Chapter 2. Nordic notes that the peripheral must accept, unless it uses an accept list (a list of the only phones it will talk to).

What the request carries

The connection request is a recipe for the whole link. In the Bluetooth core specification it holds, among other fields: a new access address for this link (so packets of other links are ignored), a starting value for the CRC, the first window to expect a packet, the connection interval, the peripheral latency, the supervision timeout, the channel map, and the hop increment from Chapter 1.

The central chooses these values. Nordic states that "the connection interval is initially set by the central", and that a peripheral can ask for a change, but the central has the final say. That matters in Chapter 9, where a phone refuses a request.

The connection event

From now on the two devices meet at every connection interval. Nordic defines a connection event as the moment the central sends a packet to the peripheral. The peripheral listens, answers 150 µs later, and the two may keep trading packets until they have nothing more to say or the next event is close. Then both turn the radio off.

Even with nothing to say, they must meet. Nordic's wording: "even if there is no useful data to send, the peers need to send empty packets to sync their clocks." The central's first packet in each event is the anchor of that event. The peripheral measures time from the last anchor to know when to wake.

Lost packets and the retry rule

Radio is noisy. Each packet carries a one bit sequence number and a one bit "what I expect next" number. When a packet is answered by the next number, it counts as acknowledged. If it is not, the sender repeats the same packet, "infinitely until an acknowledgment is received", in Nordic's words, as long as the link lives. The retry happens in the next event, on the next hop channel. Data is late, not lost.

Something must end this patience. The supervision timeout is a stop-watch on each side. It restarts whenever a valid packet arrives. If it reaches the set time with no valid packet, the link is declared lost. Zephyr's default connection parameters use 4 s. Chapter 4 shows the rule that ties the timeout to the interval.

Retry, or lose the link

Each tick is a connection event across a 4 s supervision timeout. Teal ticks are heard. Red ticks are missed. Pick what goes wrong and an interval, and read what the link does.

A toy timeline. "One bad event" misses a single event at 1 s and the data goes through in the next one. "Walk out of range" misses every event from 1 s on. The 4 s timeout is Zephyr's default; the supervision timer restarts on every valid packet.

The tick strip shows a design choice. A shorter interval means more events fit inside the timeout, so a single burst of noise is far less likely to kill the link. A longer interval makes each lost event cost more time.

Why the clocks matter

Sleeping devices do not run a precise clock. They run a slow, cheap crystal that drifts. A sleep clock accuracy of 50 ppm (parts per million) means the clock may be off by 50 µs per second. If both sides drift in opposite directions, the gap grows at 100 µs per second.

The peripheral cannot know exactly when the anchor arrives. So it opens its receiver early and keeps it open late. This is called window widening. After one second of silence between anchors, with two 50 ppm clocks, it must widen the window by about 100 µs on each side. Radio time costs 6 mA, so a wider window is wasted charge.

This is one reason a long connection interval is not free. A link that meets every 4 s must open its window 400 µs early and keep it open 400 µs late. That is about 800 µs of extra listening, more than twice the empty exchange itself (310 µs on 1M). Zephyr's header names the clock grades, such as 31 ppm to 50 ppm.

On real hardware. On an nRF52840 DK run a peripheral sample, connect from a phone, and capture with nRF Sniffer. Find the first packet of each event and check that the gap between them equals the interval. Then walk the phone away until the link drops and note how long after the last packet the disconnect appears.

A link has a 100 ms interval and a 4 s supervision timeout. A burst of interference ruins 10 consecutive events. What happens?

Chapter 4

Interval, Latency and Timeout

Turn the three connection knobs and see which trade each one makes between battery and delay

Think of two products. A chest strap sends a heart rate once a second. Nobody notices if a reading arrives 500 ms late, but the strap must run for months. A wireless mouse rests for minutes, then must react within a few milliseconds when you touch it. Both use BLE. They use different values of three numbers.

Nordic's course states the trade in one line: the connection interval is "a strict tradeoff between power consumption and low latency or delay in communication". Let us name the three numbers and pin down their units.

The three numbers

Latency needs one careful sentence, because the name is misleading. It does not add delay to the ring's own data. If the ring has something to send, it wakes at the very next event. It only lets the ring not listen when it has nothing to send. The price is paid in the other direction. A command from the phone may wait through the events the ring skips.

So the wait for a phone command is up to (latency + 1) × interval. The energy for an idle link is proportional to 1 / (interval × (latency + 1)). Latency lets you keep a fast interval for responsiveness when the ring talks, and a slow effective rate when it is quiet.

The rule that ties the timeout down

The timeout must outlast the longest legal silence. If the ring skips L events, the phone may hear nothing for (L + 1) intervals, and the standard wants room for a retry on top. The Zephyr host checks the rule before it accepts parameters:

c  (Zephyr host, bt_le_conn_params_valid)if (param->interval_min > param->interval_max || param->interval_min < 6 || param->interval_max > 3200) return false;
if (param->latency > 499) return false;
if (param->timeout < 10 || param->timeout > 3200 ||
    (param->timeout * 4U) <= ((1U + param->latency) * param->interval_max)) return false;

Read the last line with units. The timeout has 10 ms per unit and the interval 1.25 ms per unit. Convert both to milliseconds and the check says timeout > 2 × (1 + latency) × interval. Worked example: interval 30 ms, latency 4. The ring may be silent for 5 × 30 = 150 ms. Double it for retries: 300 ms. A timeout of 300 ms fails the check. A timeout of 400 ms passes.

Set the three knobs

Twenty four connection events are drawn. Blue ticks are the phone sending. Warm ticks are events the ring listens to. Hollow ticks are skipped. Change the knobs and read the numbers.

30 ms
4 events
1 s

A model. The interval stops are legal multiples of 1.25 ms (7.5 ms is 6 units). Idle current uses the same per-event cost as Chapter 0: 0.5 ms illustrative wake-up plus an empty exchange on 1M, with nRF52840 datasheet currents. The validity rule is the Zephyr host check quoted above.

Try the mouse first: interval 15 ms, latency 19. It listens every 300 ms when idle, so the quiet cost is that of a slow link, yet its own movement goes out in under 15 ms. Then try the strap: interval 1 s, latency 0. Slow and cheap, with a phone command waiting up to a second.

When the phone says no

All three values are a request. The central owns the schedule. A peripheral asks for new values with the connection parameter update. On Zephyr that is bt_conn_le_param_update(conn, BT_LE_CONN_PARAM(min, max, latency, timeout)), and the phone may pick any interval inside your range or ignore the request. Ask for a range, not one value, and read back the values the callback reports.

Choosing values: two recipes

For the chest strap, use a 1 s interval and latency 0. The quiet link averages about 8 µA in the model. A phone command may wait up to 1 s, and nobody minds. For the mouse, use a 15 ms interval and latency 19. The ring listens every 300 ms when idle and averages about 20 µA. A touch goes out within 15 ms, because the mouse wakes at the very next event.

Why not set latency to its maximum of 499 and forget it? Because skipping events makes the listening window wider. Two clocks that each drift 50 µs every second differ by 100 µs per second. At 30 ms intervals with latency 499, the ring sleeps for 15 s between listening events. The window must widen by 1.5 ms on each side, 3 ms in all, ten times the empty exchange. The saving shrinks as latency grows, and a phone command may wait 15 s.

On real hardware. On an nRF52840 DK with a power profiler, connect to a phone and log the current at 30 ms and then at 1 s intervals with nothing to send. The ratio of the two averages should be close to the ratio of the intervals, less the sleep floor.

Interval 50 ms, latency 9. What is the shortest supervision timeout the Zephyr host check accepts?

Chapter 5

GATT: A Table of Named Values

Open the attribute table inside a device and see the five operations that read, write and push its values

The phone app shows "Battery 87%". It has never seen this ring before. It knows nothing about the ring's chip, its wiring or its software. How does it find the number, and know that the number is a battery level?

The answer is a shared table. The ring keeps a list of numbered slots. Each slot has a type that says what it holds. The phone reads the list, finds the slot whose type means "battery level", and reads that slot. Both sides follow the same public rules for the layout, so any phone can read any ring's battery.

ATT: the table. GATT: the conventions.

The Attribute Protocol (ATT) defines the table. Each row is an attribute with four parts: a handle (a 16-bit row number), a type (a UUID, a number that names the meaning), permissions (who may read or write it) and a value (the bytes). The Generic Attribute Profile (GATT) sits on top and says how to group rows into meaningful things.

Two new role names appear, and they are not the same as central and peripheral. The GATT server owns the table. The GATT client reads and writes it. Usually the ring is the server and the phone is the client, but the two pairs are independent.

Reading a real table

GATT groups rows into a service (a theme, such as Battery) made of characteristics (single values, such as Battery Level). Nordic's course lists the row types, and each has a fixed type UUID. A service declaration has type 0x2800, and its value is the service's UUID. A characteristic declaration has type 0x2803. Its value holds three things: the properties, the handle of the value row, and the characteristic's UUID. Declarations are always read-only.

The next row after a declaration is the value attribute, which holds the real data. After it may come descriptors. The one you will meet most is the Client Characteristic Configuration Descriptor (CCCD), type 0x2902, readable and writable. It is the on/off switch for pushed updates. Everything between one characteristic declaration and the next belongs to that characteristic.

Standard things get 16-bit UUIDs. From the Zephyr headers: Battery Service is 0x180F, Battery Level is 0x2A19, Heart Rate Service is 0x180D and Heart Rate Measurement is 0x2A37. A custom value gets a 128-bit UUID that you generate yourself.

Five operations

Nordic names five. Each is one ATT message with a one byte opcode.

Notify and indicate work only after the client has subscribed. The client writes 0x0001 (notify) or 0x0002 (indicate) into the CCCD. Until then the server stays quiet. That is by design: a phone that does not want updates should not spend radio time on them.

Look at the bytes. A notification of the battery level 87 (0x57) from the value at handle 0x0012 is four bytes: 1B 12 00 57. That is the opcode, the handle in little-endian order, and the value. The cost of the header is three bytes, which returns in Chapter 6.

Run a GATT operation

The table is a ring's attribute table. Pick an operation. The highlighted row is the one it touches, and the bytes show every ATT message in order. Notify and indicate need the subscribe switch on.

Handles, the 87% value and the custom sample period characteristic are made up for the example. Opcodes (0x0A, 0x0B, 0x12, 0x13, 0x1B, 0x1D, 0x1E, 0x52), properties (read 0x02, write 0x08, write without response 0x04, notify 0x10) and the UUIDs 0x2800, 0x2803, 0x2902, 0x180F and 0x2A19 are the standard values, checked in the Zephyr headers. Multi-byte fields are little-endian.

Properties, permissions and discovery

Two similar words mean different things. The properties sit inside the characteristic declaration and tell the client what it may try: read, write, write without response, notify, indicate. The permissions belong to the value row itself and say what the server will allow, for example that a read needs an encrypted link. The client reads the properties first, then attempts only those operations.

How does the phone learn the table? It walks it. It asks the server for rows of type 0x2800 to list the services, then for rows of type 0x2803 inside a service to list the characteristics, then for the descriptors. This is called discovery. It costs a few round trips on every new connection, which is one reason a phone often caches the result for a device it knows. One attribute value may be at most 512 bytes; the Zephyr header cites the Core specification for that limit.

The same table in C

In Zephyr the table is built at compile time by a macro. Each macro line makes the rows you just saw. The notify call finds the value row from the declaration you hand it.

c  (Zephyr)static uint8_t level = 87;
static bool notify_on;

static void ccc_changed(const struct bt_gatt_attr *attr, uint16_t value)
{ notify_on = (value == BT_GATT_CCC_NOTIFY); }                       /* the client wrote the CCCD */

static ssize_t read_level(struct bt_conn *conn, const struct bt_gatt_attr *attr,
                           void *buf, uint16_t len, uint16_t offset)
{ return bt_gatt_attr_read(conn, attr, buf, len, offset, &level, sizeof(level)); }

BT_GATT_SERVICE_DEFINE(bas_svc,
    BT_GATT_PRIMARY_SERVICE(BT_UUID_BAS),                                  /* row 0: type 0x2800, value 0x180F */
    BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL,                        /* rows 1 and 2: declaration 0x2803, then the value */
        BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_READ,
        read_level, NULL, &level),
    BT_GATT_CCC(ccc_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE));        /* row 3: CCCD 0x2902 */

/* later, when the level changes */
if (notify_on) bt_gatt_notify(NULL, &bas_svc.attrs[1], &level, sizeof(level));

The ccc_changed callback fires when the phone writes the CCCD. Keep a flag, and do not call notify unless the phone asked. The call can fail when the stack has no free buffer, so check its return value. The Zephyr documentation lists -ENOMEM for a full ATT queue on related calls.

On real hardware. Flash a GATT sample onto an nRF52840 DK and connect with a phone tool such as nRF Connect for Mobile. Read the table, subscribe to the battery level, and compare the bytes in nRF Sniffer with 1B 12 00 57-style frames from this chapter.

A ring's battery characteristic supports notify, but the phone app sees no updates. What is the most likely cause?

Chapter 6

MTU and Data Length: How Big Is One Packet?

Follow a 100 byte record down the stack and count the headers and the packets it turns into

The ring has a 100 byte record to send: a minute of heart-rate samples. The first version of the firmware sends it with one notification call. On the phone, the app receives only 20 bytes. The rest is gone. Why 20?

Because a message is wrapped in layers, each with its own size limit, and the default limits are small. Walk the layers from top to bottom for one notification.

  1. Your value. The bytes you chose to send.
  2. ATT. Adds 3 bytes in front: 1 byte of opcode and 2 bytes of handle. The whole thing is the ATT packet, and its largest allowed size is the ATT_MTU (maximum transmission unit).
  3. L2CAP. The logical link layer. Adds 4 bytes: 2 for length and 2 for a channel number.
  4. Link layer. Carries L2CAP in packets whose payload is limited by the data length: 27 bytes by default, up to 251 with Data Length Extension (added in Bluetooth 4.2).

Put the defaults together. ATT_MTU is 23 bytes, and Nordic's course says it always starts there. Add 4 for L2CAP and you get 27, exactly one default link packet. Remove 3 for the ATT header and you get 20 bytes for your value. That is the 20.

Making room

Both devices can agree on a bigger ATT_MTU. Either one sends an MTU exchange request (ATT opcode 0x02) with the biggest packet it can receive, and the other answers (0x03) with its own. The smaller number wins. Nordic's example: a device asks for 200 and may settle on 180. Every connection starts at 23 again, so every connection must negotiate.

A bigger MTU does not by itself make the radio packet bigger. For that you need Data Length Extension, which lets one link packet hold up to 251 bytes. With both in place, the largest value in one notification is 251 − 4 − 3 = 244 bytes, the figure Nordic gives. That is why 247 is a common MTU: 247 + 4 = 251.

If the MTU is bigger than the data length, nothing breaks. Nordic notes that the data is split into pieces the size of the data length. L2CAP does the cutting and joins the pieces again at the far end. But every piece costs its own packet with its own overhead, as Chapter 1 showed. Try it.

Carve up a record

Top row: your bytes. Middle row: ATT notifications, each with a 3 byte header. Bottom row: link layer packets, with the 4 byte L2CAP header added to each notification. Change the record, the MTU and the data length.

100 bytes

A model on LE 1M with an encrypted link: each packet pair costs the phone's empty 80 µs packet, two 150 µs gaps and the ring's data packet. The 27 and 251 byte data lengths, the 4 byte L2CAP header and the 3 byte notification header are from the Nordic course and the Bluetooth specification.

Check the numbers with the defaults. A 100 byte record at MTU 23 needs five notifications of 20 bytes. Each is a 27 byte link packet taking 328 µs, and a pair costs 80 + 150 + 328 + 150 = 708 µs. Five pairs make 3,540 µs for 100 bytes.

Now turn on both upgrades, MTU 247 and 251 byte packets. The 100 bytes ride in one notification. One link packet of 107 bytes takes 968 µs, so a pair costs 1,348 µs. The record moves 2.6 times faster, and the radio is on 62% less. Bigger packets save both time and energy.

What the efficiency looks like

Compare the useful share of the bytes. At the defaults, 20 of 27 link bytes are your value: 74%. With a 244 byte value in a 251 byte packet, it is 97%. The Memfault primer applies the same idea to 27 byte link packets. Its table gives 0.226 Mbps for MTU 23, 0.294 Mbps for 185 and 0.301 Mbps for 512. The step from 23 to 185 matters a lot. The step from 185 to 512 gives only 2%.

So the practical advice is simple. Do not chase the biggest MTU. Pick one that makes a notification fill whole link packets, such as 247 with 251 byte packets, and stop. Beyond that, the radio time per byte barely changes.

The failure mode: the 20 byte surprise

The symptom is data that stops at 20 bytes, or a throughput that never beats a few kilobytes a second. The measurement is a call to bt_gatt_get_mtu(conn), which returns the current ATT_MTU. The Zephyr documentation says a notification value is limited to ATT_MTU − 3 and that larger values "have to be truncated by the sender". So the sender must read the MTU and send pieces that fit.

The fix is a request after the connection starts. A GATT client calls bt_gatt_exchange_mtu. A ring that is the server waits for the phone to start the exchange, and asks for longer link packets with bt_conn_le_data_len_update. Either way, wait for the att_mtu_updated callback before sending big values. The MTU may change later in the link, so do not cache it. The other side decides whether it grants the larger MTU.

On real hardware. On an nRF52840 DK, print bt_gatt_get_mtu in the connected callback and again after the exchange. Then send a 244 byte notification and capture it with nRF Sniffer. You should see one link packet with a 251 byte payload instead of ten small ones.

A device negotiates ATT_MTU 247 and Data Length Extension to 251. How many bytes of value fit in one notification, and in how many link packets?

Chapter 7

Throughput: Bytes Per Second, Honestly

Count how many packet pairs fit in one connection event and turn that into kilobits a second

The ring needs a firmware update. The image is 300 kB. At 20 bytes per 30 ms event the transfer would take 15,000 events, which is 7.5 minutes. The product team wants it in under two. What decides how fast BLE can move bytes?

Not the radio speed alone. The radio says 1 Mbps, but the link spends much of its time on gaps, headers and acknowledgments. To find the real rate, count what happens in one packet pair: the phone sends, the ring replies.

One packet pair, step by step

For a ring that streams data to the phone on LE 1M with 251 byte packets and encryption, here is the sequence:

  1. The phone sends an empty packet. It acts as the poll and the acknowledgment. Time: 80 µs.
  2. A mandatory gap, the inter-frame space. Time: 150 µs.
  3. The ring sends its data packet: 265 bytes on the air. Time: 2,120 µs.
  4. Another 150 µs gap, then the phone sends the next poll.

The total is 80 + 150 + 2,120 + 150 = 2,500 µs. The Memfault Interrupt primer reaches the same 2,500 µs. The ring moves 244 value bytes in that time, since 3 + 4 of the 251 bytes are ATT and L2CAP headers. So the rate is 244 × 8 bits / 2,500 µs = 781 kbps. Not 1,000.

On LE 2M the same pair costs 44 + 150 + 1,064 + 150 = 1,408 µs, since the packet takes half the time and the empty packet is 11 bytes. A long run of such pairs moves 244 × 8 / 1,408 = 1,386 kbps. The speed doubled and the throughput did not, because the 300 µs of gaps stay fixed.

How many pairs fit in one event?

Pairs must finish before the next event starts. At a 7.5 ms interval, three pairs of 2,500 µs fit (7,500 µs, a perfect fit). Three pairs carry 3 × 244 bytes per 7.5 ms, which is 781 kbps. The link rate is the same as one long pair stream, because the pairs fill the event.

Now the surprise. The Memfault primer compares 11.25 ms and 12.5 ms. At 11.25 ms only four pairs fit (10,000 µs), and 1,250 µs sits idle. At 12.5 ms five fit exactly. The model below gives 694 kbps for the first and 781 kbps for the second, a 12% gain from a slightly longer interval. The primer counts all 251 bytes, so it prints 0.713 and 0.803 Mbps, a 13% gain. The best interval for throughput is one that is a whole number of pairs.

Fill the event

The two lanes are one connection event: blue is the phone's poll, warm is the ring's data. The bar under them shows where the time of one packet pair goes. Change the settings and watch how many pairs fit.

7.5 ms

A model with the ring always having data and an encrypted link. Packet times follow the Zephyr controller formulas. The "7 packets per event" limit is the figure the Memfault primer reports for one iPhone SE on iOS 10 (with an MTU of 185 and a 15 ms minimum interval); other phones differ, so measure yours. With MTU 185, 27 byte packets, 7 packets and a 15 ms interval this model gives the primer's 0.10 Mbps.

Run the iPhone case. Choose MTU 185, turn off the 251 byte packets, turn on the 7 packet limit and pick 15 ms. You get about 97 kbps, the primer's 0.10 Mbps. Then turn the 251 byte packets on: a 7 times bigger payload per packet raises the rate to roughly 680 kbps without touching the interval. Then choose 2M: more bytes still fit in the same seven slots.

A reading of the overhead bar

The bar under the lanes divides the 2,500 µs of a 1M pair. Your 244 bytes take 1,952 µs. The other 548 µs is paid in headers (preamble, address, header, MIC, CRC and the ATT and L2CAP bytes), the 300 µs of gaps and the 80 µs poll. Roughly four fifths of the time carries your data. At MTU 23 with 27 byte packets only about a quarter does (160 µs of 708 µs). This is why Chapter 6 matters.

The failure mode: stuck near 100 kbps

The symptom is a transfer that never gets above a few tens of kilobytes a second, on a link the datasheet says can do ten times more. The measurement comes from a sniffer capture. Count the packets in one event, check the longest payload seen, and read the MTU. The Memfault primer adds that the More Data bit shows which side ends the event.

The fix follows the cause. If packets are 27 bytes, request Data Length Extension. If the MTU is 23, run the exchange. If the phone caps packets per event, raise the bytes per packet, ask for the 2M PHY, and pick an interval that is a whole number of pairs. Longer intervals mainly add latency, but do not cut throughput when data streams without a break.

A firmware update shows the payoff. At 781 kbps the 300 kB image needs about 3 s of link time. Real transfers are slower, because flash writes, acknowledgments in the application and the phone all take time, which is why the rate you measure is the number that counts.

On real hardware. Run Nordic's throughput sample on two nRF52840 DKs and change the PHY, MTU and interval in its settings. Compare the printed rate with this chapter's model. The first gap you find is usually the phone, so repeat with a phone as the central.

On LE 1M with 251 byte packets, one packet pair takes 2,500 µs. How many pairs fit in an 11.25 ms event, and what follows?

Chapter 8

The Energy Bill

Add up where the charge goes, per event and per byte, and see how many days a small cell lasts

The ring passes its tests on the bench and ships. A month later the returns arrive: "battery lasts nine days". The firmware did what it was told. What was it told to do that was so expensive?

To answer, we need an exact bill. The currency is charge: current multiplied by time, written in microcoulombs (µC) or, for a battery, in milliamp-hours (mAh). A battery of 220 mAh holds 220,000 µAh. If the average current is 10 µA, the battery lasts 22,000 hours, which is 917 days.

Three items on the bill

The data item hides a lesson about packet size. A full 251 byte packet pair costs about 16 µC for 244 value bytes, or 65 nC a byte. A tiny 4 byte notification is a 25 byte packet. The pair still pays for the poll, the gaps and the headers: about 3.7 µC for 4 bytes, or 915 nC a byte, fourteen times more. Nordic's advice is the same in plain words: send as much data as possible in one packet, to cut radio-on time, power and overhead.

Two ways to send a reading every second

Take a ring that makes 4 bytes of data per second. Plan A keeps a 100 ms interval with no latency, and notifies every second. Plan B keeps the same 100 ms interval but gives the ring a latency of 9, so it listens once a second, and it batches 30 seconds of readings (120 bytes) into one burst. Compare them in the budget device. Plan A averages about 56 µA and Plan B about 8 µA, a gap of nearly 7 times for the same data.

Budget the link

Pick a recipe or set the knobs. The bars are on a log scale. Watch which item is the biggest, and what happens to the days when you change it.

4 bytes a second
1 s
100 ms
0 events

A model on LE 1M with MTU 247 and 251 byte packets. Currents: nRF52840 datasheet (6.40 mA transmit at 0 dBm, 6.26 mA receive, 3.16 µA asleep with the timer, DC/DC, 3 V). The 0.5 ms per event for waking is illustrative. The 220 mAh cell is an illustrative size and the model ignores the CPU, the sensor, the regulator and voltage sag, which the next lesson in this track covers.

Try the mouse recipe. It sends little but needs fast response, so it keeps a 15 ms interval and a high latency. The idle link cost falls to a small fraction of the always-on case, and the response to the user's movement still goes out at the next event.

The floor is not one number

Even the sleep floor depends on a choice. The nRF52840 datasheet gives several System ON idle currents. With the timer running from its internal RC clock and no RAM kept, it is 1.50 µA. With all 256 kB of RAM kept, it is 3.16 µA. System OFF with no RAM kept is 0.40 µA, but then nothing runs and nothing wakes it except a reset or a pin event.

A connected ring needs its RAM, since the link state lives there. So 3.16 µA is a fair floor for this lesson. A real design adds the sensor, the regulator and the flash, each with its own quiet current. The next lesson, The Coin-Cell Year, adds the peak current and voltage sag of a real cell.

The failure mode: the interval that never relaxed

The symptom is a battery that dies in days. The measurement is a current trace from a power profiler, where you see a spike every few milliseconds even though the ring sends nothing. The cause in this ring: the phone app asked for the fastest interval to speed up setup, and the phone granted 15 ms. Nothing ever asked for a slower one. The ring sat in the fast mode for its whole life.

The fix is firmware policy. Once the burst of work is done, the ring asks for a relaxed set with bt_conn_le_param_update, for example a range of 500 ms to 1 s with some latency. It also keeps the range wide enough for the phone to say yes. Chapter 9 shows the call. The saving in this device is the same dial you just turned.

On real hardware. Put a Nordic Power Profiler Kit II in series with an nRF52840 DK, connect to a phone, and read the average current at two intervals. Multiply the idle average by 24 hours to get charge per day, then subtract it from your battery's budget.

A ring sends 4 bytes every second and wastes battery. Which change usually saves the most?

Chapter 9

On Real Silicon: Zephyr Calls and Three Symptoms

Write the firmware that sets up a link on an nRF52840, then diagnose the failures that the earlier chapters predicted

Everything so far was a model. Now the same ideas run as firmware. The example part is the Nordic nRF52840 and the example stack is Zephyr, which is the base of nRF Connect SDK. A Bluetooth host and controller run on the chip, and your code talks to the host through callbacks.

The pattern is event driven. You do not poll the radio. You register callbacks, start advertising, and the stack calls you when something happens: a connection, a parameter change, a disconnect. The first job inside connected is to ask for better settings than the defaults.

The connection set-up in C

c  (Zephyr, nRF52840 peripheral)static void connected(struct bt_conn *conn, uint8_t err)
{
    if (err) { return; }
    bt_conn_le_phy_update(conn, BT_CONN_LE_PHY_PARAM_2M);              /* Ch 1: ask for LE 2M */
    bt_conn_le_data_len_update(conn, BT_LE_DATA_LEN_PARAM_MAX);        /* Ch 6: 251 byte link packets */
}

static void params_updated(struct bt_conn *conn, uint16_t interval, uint16_t latency, uint16_t timeout)
{ printk("interval %u x 1.25 ms, latency %u, timeout %u x 10 ms\n", interval, latency, timeout); }

BT_CONN_CB_DEFINE(conn_cbs) = { .connected = connected, .le_param_updated = params_updated };

/* later, once the burst of work is over: relax the link (Ch 4, Ch 8) */
bt_conn_le_param_update(conn, BT_LE_CONN_PARAM(
    BT_GAP_MS_TO_CONN_INTERVAL(500), BT_GAP_MS_TO_CONN_INTERVAL(1000),
    2, BT_GAP_MS_TO_CONN_TIMEOUT(8000)));            /* 8 s > 2 x (1 + 2) x 1000 ms = 6 s: valid */

int main(void)
{
    bt_enable(NULL);                                                   /* start the host and the controller */
    bt_le_adv_start(BT_LE_ADV_CONN_FAST_1, ad, ARRAY_SIZE(ad), NULL, 0);   /* Ch 2 */
    return 0;
}

Each name is a real Zephyr call from this chapter's source reading. The macros BT_GAP_MS_TO_CONN_INTERVAL and BT_GAP_MS_TO_CONN_TIMEOUT convert milliseconds into the 1.25 ms and 10 ms units of Chapter 4. The interval range 500 ms to 1 s is deliberate. A range gives the central room to say yes.

The MTU is shared work. The GATT client starts the exchange, with bt_gatt_exchange_mtu, and a phone usually does so. A ring that acts as server must have buffers big enough to accept it. In Zephyr they come from Kconfig options such as CONFIG_BT_L2CAP_TX_MTU and CONFIG_BT_BUF_ACL_RX_SIZE, and the controller needs CONFIG_BT_CTLR_DATA_LENGTH_MAX and CONFIG_BT_CTLR_PHY_2M for the packet size and the 2M radio. The callback att_mtu_updated tells you the result.

The phone has the last word

Every request here is a request. Nordic puts it directly: a peripheral may ask, but the central has the final say. The Memfault primer reports that an iPhone on iOS 10 and later allowed a minimum interval of 15 ms for normal apps and sent 7 packets per event. Other phones differ, and they change with software updates. So the firmware must read back what it got, in le_param_updated, and adapt.

Where your callbacks run

The Zephyr documentation notes that the MTU exchange callback runs in a thread context, never in an interrupt service routine. The same holds for connection callbacks. So you may call most stack functions from inside them, but you should not block there. A callback that waits for a flash write holds up the stack's own work. The usual pattern is to set a flag or post a message to your own thread, and do the slow work there.

A good order at connect

  1. Connected. Log the interval, latency and timeout. They are the phone's choice, not yours.
  2. Ask for speed. Request the 2M PHY and the longest data length. Wait for the update callbacks.
  3. Let the client set the MTU. Read it with the update callback before you send large values.
  4. Do the burst of work. Send the history, or the firmware image.
  5. Relax. Ask for a range of slow intervals with some latency. Read back what you got.

That list is the whole discipline of Chapters 4 to 8 in five lines. Each step also names its measurement: the callback values, a sniffer capture, and a power trace.

After the link ends

In the usual set-up, connectable advertising stops when a connection starts. When the phone walks away and the supervision timeout fires, the ring is silent and invisible. So the disconnected callback must start advertising again, with the fast interval, or the user will find a dead ring. The callback also carries a reason code. Log it. A reason that says the timeout fired points at range or interference. A reason that says the remote side hung up points at the phone app.

Logging the reason, the granted parameters and the MTU at every disconnect gives you a free field record. Over a month it tells you which phones give you which intervals, without a single sniffer capture.

Diagnose it

Four tickets arrive in the bug tracker. Each has the symptom, and the measurement that a bench engineer would take. Pick the cause. The device tells you the fix.

Four tickets

Read the symptom and the measurement, then pick the most likely cause. A wrong pick is explained, not just marked.

The tickets are teaching cases built from this lesson's numbers. The 100 kbps case reproduces the primer's phone figure with this lesson's model; the others use the datasheet currents and the Zephyr parameter rule.

Each fix is one line of firmware or one Kconfig option, but each needed a measurement first. The sniffer showed packet sizes. The power profiler showed the interval. The parameter callback showed the refusal. Guessing from the code would have found none of them. Chapter 10 collects the numbers you need to check these quickly.

On real hardware. Run this code on an nRF52840 DK. Connect from a phone, log params_updated, then use nRF Sniffer to compare the interval you see on the air with the one you asked for. Repeat with two phones if you can.

Your ring asks for a 7.5 ms interval and the callback reports 30 ms. What is the right reading?

Chapter 10

Field Guide: The Numbers, the Checklist, the Code

Keep one page of BLE facts at hand, and know where to go next in the Firmware track

You can now follow a BLE link from the radio to the attribute table, and from the interval to the battery. This page collects what to remember, and what to check first when a link misbehaves.

The one-paragraph summary

A BLE device keeps its radio off almost all the time. It advertises on channels 37, 38 and 39 so a phone can find it. The phone sends a connection request that sets the schedule. The two then meet at every connection event, hopping across 37 data channels, trading packets that carry a 4 byte L2CAP header and an ATT message. A server keeps a GATT table of services and characteristics. Three knobs, the interval, the peripheral latency and the supervision timeout, trade delay against power. The MTU, data length and PHY set how many bytes ride in each packet pair, and the interval sets how many pairs fit. The central owns the schedule, so firmware asks and then reads back.

The numbers that matter

WhatNumberWhy it matters
Channels40: advertising 37, 38, 39 at 2402, 2426, 2480 MHz; data 0 to 36Where the radio listens, and what hopping uses
PHYs1M, 2M, Coded S=2 (500 kbps), Coded S=8 (125 kbps)Speed against range
Advertising interval20 ms to 10.24 s, 0.625 ms steps, plus 0 to 10 ms randomFindability against current
Legacy advertising data31 bytes (37 byte payload with the 6 byte address)What your AD structures must fit
Connection interval6 to 3200 units of 1.25 ms: 7.5 ms to 4 sDelay and idle current
Peripheral latency0 to 499 eventsSkip listening when idle
Supervision timeout10 to 3200 units of 10 ms: 100 ms to 32 s; must exceed 2 × (1 + latency) × intervalHow long a silent link survives
Inter-frame space150 µsFixed gap in every packet pair
ATT_MTU23 at start; notification value is MTU − 3; attribute value up to 512 bytesThe 20 byte surprise
Link packet payload27 bytes, or up to 251 with Data Length Extension; L2CAP adds 4244 value bytes fit one full packet
Packet time, LE 1Mempty 80 µs; 27 bytes 328 µs; 251 bytes 2,120 µsCost of overhead
Packet time, LE 2M and Coded251 bytes on 2M 1,064 µs; empty on S=8 720 µs; largest on S=8 17,040 µsLong packets need long intervals on Coded
Packet pair, 251 bytes1M 2,500 µs (781 kbps); 2M 1,408 µs (1,386 kbps)The upper bound on throughput
GATT row typesservice 0x2800, characteristic 0x2803, CCCD 0x2902How to read any table
ATT opcodesread 0x0A, write 0x12, write command 0x52, notify 0x1B, indicate 0x1D, confirm 0x1E, MTU request 0x02What a sniffer shows
nRF52840 currents (DC/DC, 3 V)transmit 0 dBm 6.40 mA; receive 1M 6.26 mA; System ON idle with timer 3.16 µAThe bill
Quiet link, modelabout 8 µA at 1 s; 52 µA at 100 ms; 168 µA at 30 ms; 663 µA at 7.5 msWhy intervals matter

The checklist

  1. Advertising. Flags, service UUID and a short name fit in 31 bytes. Fast interval at first, slow after.
  2. Parameters. Ask for a range. Satisfy timeout > 2 × (1 + latency) × interval. Read back the granted values.
  3. Throughput. Request 2M, 251 byte packets and a large MTU. Choose an interval that holds a whole number of packet pairs.
  4. GATT. Notify only after the CCCD is written. Check the return value of every notify.
  5. Power. Relax the link when work is done. Batch small readings. Measure with a profiler, not by reading the code.
  6. Evidence. Keep a sniffer capture of a good connection. It shows interval, packet size and MTU at a glance.

The core as code

The whole timing model of this lesson is a dozen lines. This sketch uses the Bluetooth packet format as the Zephyr controller states it: how long a packet takes, and how many packet pairs fit in an interval.

c/* time on the air of one uncoded data packet, in microseconds */
static uint32_t pdu_us(uint32_t payload, bool two_m)
{
    uint32_t mic = payload ? 4 : 0;                         /* encrypted, non-empty */
    uint32_t preamble = two_m ? 2 : 1;
    uint32_t bytes = preamble + 4 + 2 + payload + mic + 3;   /* preamble, address, header, data, MIC, CRC */
    return bytes * 8 / (two_m ? 2 : 1);
}

/* one poll from the phone, a 150 us gap, the ring's packet, a 150 us gap */
static uint32_t pair_us(uint32_t payload, bool two_m)
{ return pdu_us(0, two_m) + 150 + pdu_us(payload, two_m) + 150; }

/* value bytes per second if the ring always has data */
static uint32_t bytes_per_s(uint32_t interval_us, uint32_t mtu, bool two_m)
{
    uint32_t payload = mtu + 4;                              /* one notification in one link packet, payload at most 251 */
    uint32_t pairs = interval_us / pair_us(payload, two_m);
    return (1000000UL / interval_us) * pairs * (mtu - 3);
}

Call bytes_per_s(7500, 247, false): pair_us is 2,500, so 3 pairs fit, 133 events a second, and the result is 133 × 3 × 244 = 97,356 bytes a second, about 779 kbps. The model in the devices uses the same arithmetic.

Where this sits

Hardware buses led here (Buses on the Wire, and the BLE chapter of Hardware Interfacing). The sleep and battery maths of this track continue in Sleep, Wake and the Battery Budget. Interrupt-driven radio code builds on Interrupts and DMA, and the project setup is in Zephyr in Practice.

Keep going

Sources

Facts about the Bluetooth standard that the pages above do not state in words, such as the connection request fields, the sequence numbers and window widening, come from the Bluetooth Core Specification. The Coded PHY currents and 2M currents are not on the datasheet page used here, so the models reuse the 1 Mbps values.

The takeaway. A BLE link is a schedule. Everything you can tune is a choice about how often to meet, how long to stay, and how many useful bytes to carry each time. Fix the schedule first, then fill it.

Now press Present or Teach and explain one connection event out loud, from memory: who sends first, what the 150 µs gap is, why the ring may skip events, and how big a notification can be. Then go back to the instrument at the top, pick 2M and MTU 247, drag the interval from 7.5 ms to 1 s, and say why the data rate barely moves while the quiet current falls by almost two orders of magnitude.

Bluetooth LE from Radio to GATT
Nordic Developer Academy, Bluetooth LE Fundamentals · Back to Gleams