BLE: Advertising, Connections, and Data Design
A BLE advertisement is 31 bytes shouted into the room. Beacon's whole job fits in 14 of them.
🎯 By the end you'll understand
How Bluetooth Low Energy divides 2.4 GHz into forty channels, why exactly three of them carry advertisements, and where they sit relative to Wi-Fi. What is physically on the air during one advertising event — preamble, access address, header, address, your data, CRC — and how to convert that into microseconds and then into millicoulombs. The four dials that set a tag's energy cost: interval, packets per event, transmit power, and payload length, and which of them actually matters. When a connection is worth its overhead and when it is pure loss. And how to design a fourteen-byte payload that survives a gateway, an MQTT broker, and a database without lying to any of them.
KEY INSIGHTThe interval is not the dial that matters
The example project advertised every 100 ms, so the product advertised every 100 ms. Someone eventually widened it to 1.28 seconds — a factor of nearly thirteen — and measured the battery life again. It went from 27 days to 48. The problem was never the interval. It was that the radio never went away.
There are two completely different ways to be a BLE tag, and they differ by three orders of magnitude in energy. The obvious one is to advertise: configure an interval, start the advertiser, and let the controller emit packets forever. The other is to sleep, and occasionally wake up to shout: sit in deep sleep at microamps, wake on a timer or an interrupt, bring the radio up, send a burst, and go back to sleep. The first architecture's floor is the controller staying alive between events, which is milliamps. The second architecture's floor is deep sleep, which is 8 µA. Every interval you can choose in the first architecture is worse than the second, and the first is what every example project does, because examples are written to demonstrate a protocol rather than to survive six months.
Price a radio in millicoulombs per report, never in milliamps. A packet on the 1 M PHY is (16 + payload) bytes at 8 µs per byte — a couple of hundred microseconds — and at 85 mA that is roughly 0.02 mC. Three of them is 0.07 mC. Beacon's entire wake window is 1.8 mC. So the packets are four percent of the wake, and the wake is a hundred percent of the argument. Bytes are nearly free; waking up is not; staying awake is ruinous. Every optimisation in this lesson follows from that ranking.
HOW IT WORKSForty channels, three of them special
BLE divides the 2.4 GHz ISM band into forty channels of 2 MHz, running from 2402 MHz to 2480 MHz. Thirty-seven of them are data channels used inside connections, where the two devices hop between them according to a shared sequence — adaptive frequency hopping, which lets a connection route around a channel that is being clobbered by a microwave oven or a Wi-Fi access point.
The other three are the primary advertising channels, and they cannot hop, because an advertiser and a scanner that have never met have no shared sequence to agree on. They are fixed, and their frequencies are chosen with obvious care:
| Channel | Frequency | Position relative to Wi-Fi |
|---|---|---|
| 37 | 2402 MHz | Below Wi-Fi channel 1's occupied band |
| 38 | 2426 MHz | In the gap between Wi-Fi channels 1 and 6 |
| 39 | 2480 MHz | Above Wi-Fi channel 11's occupied band |
The three sit at the edges and in a gap of the three non-overlapping 2.4 GHz Wi-Fi channels that dominate the band. That placement is the reason an advertising burst on all three channels is meaningfully more robust than three repeats on one: it buys frequency diversity against both interference and the multipath fading of Lesson 4.5, because a null 24 or 54 MHz away is a different null.
LE 1M is the original: GFSK at 1 Mbit/s, one bit per microsecond, universally supported. LE 2M (Bluetooth 5) doubles the symbol rate, halving on-air time — worth real energy on a long transfer, at the cost of roughly 3 dB of sensitivity and a scanner that must support it. LE Coded goes the other way, adding forward error correction at S=2 or S=8 to buy roughly 5 dB or in the region of 12 dB of link budget at one-half or one-eighth the rate. Beacon uses LE 1M for the only reason that matters in a pilot: everything scans it. Coded PHY would buy range Beacon does not need (Lesson 4.5 showed 21 dB of margin) at eight times the on-air time and a gateway that must be configured for it.
HOW IT WORKSInside an advertising event
An advertising event is one pass across the enabled advertising channels. The advertiser transmits the same PDU on channel 37, then 38, then 39, with a short turnaround between each, and the whole event is over in a couple of milliseconds. Then it waits for the advertising interval and does it again.
On the air, a legacy advertising packet on the 1 M PHY is:
Three parameters govern the event, and it is worth being precise about each.
Advertising interval: 20 ms to 10.24 s
Specified in units of 0.625 ms, so the register value 0x00A0 is 160 × 0.625 ms = 100 ms. Twenty milliseconds is the floor for legacy advertising; 10.24 s is the ceiling. To that interval the controller adds advDelay, a pseudo-random 0–10 ms, on every event. That delay exists so that two advertisers with identical intervals do not collide forever — without it, two tags that happen to start in phase would jam each other permanently.
Advertising type: connectable, scannable, or neither
ADV_IND is connectable and scannable; after transmitting on each channel the advertiser must open a receive window to listen for a CONNECT_IND or SCAN_REQ. That receive window costs current on every channel of every event, and if you never accept connections it buys nothing. ADV_NONCONN_IND is neither: transmit and leave. For a tag that only ever broadcasts, this is free energy, and it is what Beacon uses.
Channel map
Any subset of 37, 38, 39. Dropping to one channel cuts the event's radio time by two thirds and throws away the frequency diversity that makes an indoor link reliable. It is a legitimate choice in a controlled RF environment with a gateway two metres away, and a bad one everywhere else.
Bluetooth 5 added extended advertising: a small ADV_EXT_IND on the primary channels points a scanner at an AUX_ADV_IND on one of the 37 data channels, where the payload can be 254 bytes in a single PDU and more when chained. It solves the 31-byte problem properly. It costs more on-air time, more complexity, and — decisively for a pilot — a scanner that supports it, which not every phone, dongle, and gateway stack does equally well. Beacon's data fits in 14 bytes. Reach for extended advertising when your data genuinely does not fit, not because 31 feels tight.
SEE ITAdvertising energy dial
The same four dials appear in every BLE tag's configuration, and the widget prices all of them at once. It also does the thing most calculators leave out: it models the gateway, because a report that nobody hears is not a report. Two requirements are in tension — R1's six months and R4's two-second report after a motion event — and the point of the exercise is to find out which dial resolves the tension and which one cannot.
Four things to try, in this order. One: switch to "advertise continuously" and leave everything else alone. The interval slider now controls a device whose radio never sleeps, and no value of it reaches six months — drag it from 100 ms to 10 s and watch the life improve by a factor of two rather than a factor of a hundred, because the idle floor dominates. That is the opening quote, reproduced. Two: back in burst mode, push the payload from 14 bytes to the full 31. The average current barely moves: seventeen extra bytes cost 136 µs of air time per packet, which is nothing against a 45 ms wake. Bytes are cheap. Three: raise packets per event from 3 to 9. Now you see a change, because packets are the only radio dial with real leverage — and you also see the diminishing return, since three channels already give you the diversity. Four, and the important one: put the gateway's scan duty cycle at 20 % and read the latency. R4 is now missed by minutes, and nothing you can do on the tag fixes it. The two-second requirement lives at the gateway.
IN PRACTICEDesigning the fourteen bytes
The 31 bytes of AdvData are not a flat buffer. They are a sequence of AD structures, each one a length byte, an AD type byte, and that many minus one bytes of data. Standard types include Flags (0x01), Complete Local Name (0x09), Service UUIDs, and — the one that matters for a proprietary sensor — Manufacturer Specific Data, type 0xFF, whose first two bytes must be a Bluetooth SIG company identifier in little-endian order.
Beacon's payload occupies exactly one AD structure. Count it carefully, because the arithmetic trips people:
| Byte(s) | Field | Why this size |
|---|---|---|
| 0 | Length = 13 | Counts the type byte plus the twelve data bytes. Not part of the "payload" but very much part of the 31. |
| 1 | AD type 0xFF | Manufacturer Specific Data. |
| 2–3 | Company identifier | 0xFFFF while in development — the SIG reserves that value for internal and testing use. A shipping product needs a real assigned identifier. |
| 4 | Firmware version | One byte, so a gateway can decode old and new units during a staged OTA (Lesson 4.9). Omitting this is the mistake you make once. |
| 5 | Sequence number | Increments per report, wraps at 256. Lets the dashboard count losses and de-duplicate the three packets of one burst. Lives in RTC memory so it survives deep sleep. |
| 6–7 | Temperature, int16, °C × 100 | 0.01 °C resolution against an SHT40 accurate to ±0.2 °C class — generous, but int16 is free and a smaller field would need bit packing that the gateway then has to get right. |
| 8 | Relative humidity, uint8, % | 1 % quantisation adds ±0.5 % to a sensor already well inside R3's ±3 % budget. |
| 9–10 | Battery, uint16, mV | Millivolt resolution over 2000–4300 mV. Two bytes is the natural size; one byte would need an offset-and-scale that someone will misread. |
| 11 | Flags | Bitfield: charging, self-test result, OTA-pending, sensor fault. Free real estate you will be grateful for. |
| 12 | Moved since last report | The accelerometer's verdict. A whole byte for one bit, because the alternative is packing it into flags and then arguing about it during bring-up. |
| 13 | CRC-8 | End-to-end integrity — see the caveat below. |
typedef struct __attribute__((packed)) { uint16_t company_id; // 0xFFFF — SIG-reserved for internal/testing use uint8_t fw_ver; uint8_t seq; // RTC_DATA_ATTR counter from 4.3, wraps at 256 int16_t temp_c100; // °C × 100, little-endian uint8_t rh_pct; uint16_t batt_mv; uint8_t flags; uint8_t moved; uint8_t crc8; } beacon_pdu_t; _Static_assert(sizeof(beacon_pdu_t) == 12, "payload drifted — check packing"); static esp_ble_adv_params_t adv_params = { .adv_int_min = 0x00A0, // 160 × 0.625 ms = 100 ms .adv_int_max = 0x00A0, .adv_type = ADV_TYPE_NONCONN_IND, // no RX window after each packet .own_addr_type = BLE_ADDR_TYPE_RANDOM, .channel_map = ADV_CHNL_ALL, // 37, 38 and 39 — frequency diversity .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; void beacon_advertise(const beacon_pdu_t *pdu) { uint8_t raw[14]; raw[0] = 1 + sizeof *pdu; // 13: the type byte plus 12 data bytes raw[1] = 0xFF; // AD type: Manufacturer Specific Data memcpy(&raw[2], pdu, sizeof *pdu); esp_ble_gap_config_adv_data_raw(raw, sizeof raw); esp_ble_gap_start_advertising(&adv_params); // …stop after three events, then esp_deep_sleep_start() — see 4.3 }
Against: the BLE link layer already appends a 24-bit CRC to every packet, and the controller discards anything that fails it. Your application will never see a corrupted advertisement. A payload CRC is therefore, on the air, pure waste — one byte and 8 µs per packet.
For: the air is not the only place the data travels. It goes from the controller into the gateway's host stack, into a Python script, into a JSON document, through an MQTT broker, into a database. Every one of those is a place where a field can be truncated, an endianness assumption can flip, or a length can be miscounted — and none of those failures are caught by a link-layer CRC that was checked and discarded three hops earlier. An end-to-end CRC turns "the dashboard says 214 °C" from a mystery into a rejected record with a log line.
Beacon keeps it, on the grounds that a 25-unit pilot's biggest risk is a gateway bug rather than a radio one, and that one byte out of seventeen spare costs nothing. That is a judgement about where the errors will come from, and it should be written down as one — not defended as though the link-layer CRC did not exist.
COMPARISONConnections and GATT: when the overhead is worth it
A connection is a scheduled, bidirectional relationship. The two devices agree a hopping sequence and a connection interval — 7.5 ms to 4 s, in 1.25 ms units — and both must wake at every connection event, even when neither has anything to say. Peripheral latency softens that: the peripheral may skip up to a configured number of consecutive events (up to 499) if it has no data, while the central still wakes for each one. And a supervision timeout (100 ms to 32 s) decides how long silence is tolerated before the link is declared dead.
On top of that sits GATT: a hierarchy of services, each containing characteristics, each with a value and a set of permissions. A central can read or write a characteristic, and a peripheral can push a notification (unacknowledged) or an indication (acknowledged) when a value changes. It is a sensible, discoverable data model, and it costs a connection to use.
| Non-connectable advertising | Connection + GATT | |
|---|---|---|
| Direction | One way, broadcast to anyone listening | Two way, one central at a time |
| Data per report | 31 bytes of AdvData (14 used) | Effectively unlimited, at 20+ bytes per notification |
| Energy per report | Roughly 0.07 mC of packets on top of the wake | Several milliCoulombs — setup, several connection events, teardown |
| Latency | Bounded by the scanner's duty cycle | Bounded by the connection interval, once established |
| Receivers | Any number of gateways simultaneously | Exactly one |
| Security | None inherent — anyone can hear it | Pairing, bonding, encryption available |
The decision rule is not subtle. If the data fits in an advertisement and the recipient is a fixed gateway, advertise: it is cheaper, it reaches every gateway in range at once, and it has no state to get wrong. Connect when you need a conversation — configuration, a firmware image, a diagnostic dump, anything where the device must receive as well as send. Beacon does exactly this: it broadcasts forever, and it accepts a connection only in the OTA path of Lesson 4.9, entered deliberately by holding the button at wake.
BEACONBeacon: the payload, live
The Stage 4 milestone says the BLE payload is live and decoded at a gateway. Here is the configuration that satisfies it, entirely from the canon:
| Setting | Value | Consequence |
|---|---|---|
| Advertising type | Non-connectable, non-scannable | No receive window after any packet. Pure transmit. |
| Packets per burst | 3 — one each on 37, 38, 39 | Frequency diversity against fading and Wi-Fi (Lesson 4.5). |
| Transmit power | 0 dBm | Where R1 and R2 cross. The canon's active window is a 0 dBm number. |
| AdvData used | 14 of 31 bytes, one AD structure | 240 µs on air per packet. Seventeen bytes spare for Rev B. |
| Between bursts | Deep sleep — no advertising interval at all | The 8 µA floor, not a controller idling at milliamps. |
| Report period | 60 s, plus motion wakes | 1.8 mC per report ⇒ 30 µA ⇒ 38 µA average ⇒ three years on paper, six derated months. |
The last row of that table is the whole of Lesson 4.3, and the point of putting it here is that the advertising interval never appears in it. Beacon has no advertising interval in any meaningful sense: the controller is only alive for the few milliseconds it takes to emit three packets, and between reports the chip is in deep sleep with the radio unpowered. That is what "sleep and burst" means, and it is the single decision that separates a six-month tag from a six-week one.
Two honest gaps remain at this point in the project. First, the sequence number wraps at 256, which at one report a minute is four hours and sixteen minutes. That is fine for gap detection over a scanning window and useless as a global counter; the gateway must reconstruct absolute report numbers from its own clock. Second, the advertisement is public. Anyone with a phone can read Beacon's temperature, battery, and movement flag, and can track the device's static random address as it moves between rooms. For a tag on a tool cart in a workshop that is an acceptable disclosure, and it should be stated as an accepted risk in the pilot documentation rather than discovered by a customer. Lesson 4.9 covers what changes when it is not acceptable.
WEAKNESSWhere this bites
Every vendor BLE example advertises continuously, because that is how you demonstrate advertising. Copy it into a battery product and you inherit a controller that never sleeps, which is a floor of milliamps that no interval setting can remove. The tell is a device whose measured average current does not drop proportionally when you double the interval: if going from 100 ms to 200 ms improves life by 20 % rather than 90 %, you are not paying for packets, you are paying for being awake. The fix is architectural — deep sleep between bursts — not a parameter change.
ADV_IND is the default in most examples and it obliges the advertiser to open a receive window after transmitting on each channel, listening for connection and scan requests that, in your product, will never come. You pay receive current three times per event for a feature you do not have. Worse, you also pay for every SCAN_REQ that a passing phone sends, which turns a nearby crowd into a load on your battery. If the device is a broadcaster, say so in the advertising type.
Two mistakes that both come from ignoring the other side of the link. First, the 31 bytes are shared: a Flags structure is 3 bytes, a short local name is another 2 plus its characters, and a 128-bit service UUID is 18. Add a name "for debugging" and your carefully sized payload no longer fits, at which point the stack silently truncates or refuses. Second — and this one costs entire pilots — the report latency a customer experiences is set by the scanner's duty cycle at least as much as by your advertising. A tag that bursts perfectly into a gateway that listens 20 % of the time misses four bursts out of five, and R4's two seconds becomes minutes. Specify the gateway's scan window and interval as part of the product, not as somebody else's configuration.
KEY INSIGHTHow this connects
- Sleep Modes and the Power Budget (4.3) — the 1.8 mC wake window that this lesson decomposed into boot, sensors, and radio. The packets turned out to be four percent of it.
- Wireless Fundamentals: dBm, Link Budget, and Antennas (4.5) — why three channels rather than three repeats, and why 0 dBm rather than +9. The link budget and the energy budget are the same argument.
- Wi-Fi, MQTT, and When Not to Use Wi-Fi (4.7) — next: the same report sent over Wi-Fi, priced in the same millicoulombs, and the architecture that follows from the comparison.
- OTA Updates, Provisioning, and Security Basics (4.9) — the one place Beacon does accept a connection, and the firmware-version byte in the payload that makes a staged rollout observable.
Beacon can now say what it knows in fourteen bytes for a twentieth of a millicoulomb. The next lesson asks what the same sentence costs in a different language.
GLOSSARYKey terms introduced
- Primary advertising channels
- Channels 37, 38, and 39, at 2402, 2426, and 2480 MHz. Fixed rather than hopping, because an advertiser and an unknown scanner share no hop sequence, and placed in the gaps around the common Wi-Fi channels.
- Advertising event
- One pass across the enabled advertising channels, transmitting the same PDU on each. Repeats every advertising interval plus advDelay.
- Advertising interval
- 20 ms to 10.24 s, in units of 0.625 ms. Meaningless for a device that deep-sleeps between bursts, which is why Beacon's energy budget never mentions it.
- advDelay
- A pseudo-random 0–10 ms added by the controller to each advertising event, so that two advertisers with identical intervals do not collide permanently.
- ADV_NONCONN_IND
- A non-connectable, non-scannable advertisement. The advertiser transmits and leaves, opening no receive window — the cheapest way to broadcast.
- AD structure
- The unit of AdvData: a length byte, an AD type byte, and the data. Manufacturer Specific Data is type 0xFF and begins with a two-byte SIG company identifier.
- Peripheral latency
- The number of consecutive connection events a peripheral may skip when it has nothing to send, up to 499. The main energy lever inside a connection.
- Extended advertising
- A Bluetooth 5 mechanism where a small PDU on a primary channel points a scanner at a larger one on a data channel, allowing 254 bytes and more when chained. Costs air time and scanner support.
ACTIVE RECALLCheck your understanding
Answer in your own words first, then reveal.
1Compute the on-air time of one Beacon advertising packet, and then say what fraction of the 1.8 mC wake window the three-packet burst represents.›
A legacy advertising packet on the 1 M PHY is preamble 1 + access address 4 + header 2 + AdvA 6 + AdvData + CRC 3 = 16 + AdvData bytes. Beacon uses 14 bytes of AdvData, so 30 bytes. At 1 Mbit/s each byte is 8 µs, giving 240 µs per packet.
Three packets is 720 µs of transmission. At a transmit current in the region of 85 mA that is 0.72 ms × 85 mA ≈ 0.061 mC, plus a little for the turnarounds — call it 0.07 mC. Against the canon's 1.8 mC wake window that is about four percent. The other 96 % is booting the chip, reading the sensors, and starting the radio. This is the reason payload size is not an energy lever and waking up is.
2A colleague proposes cutting the advertising burst from three packets to one to save energy. Give the energy saving and the reason to refuse.›
The saving is two packets' worth: roughly 0.048 mC out of 1.8, or about 2.7 % of the wake window, which moves the average current from 38 µA to about 37.2 µA and buys around five days on a three-year paper life. Derated, it is under a day of the six months.
The reason to refuse is that the three packets are not repetition, they are frequency diversity. Channels 37, 38, and 39 sit 24 and 54 MHz apart, and indoor multipath fading is frequency-selective — a null deep enough to kill 2402 MHz very often leaves 2480 MHz intact. Dropping to one channel means a tag standing in the wrong place loses every report rather than one in three, and the failure is persistent rather than transient because the tag does not move. Trading a measurable reliability property for under a day of battery life is a bad trade, and it is the kind that only looks good in a spreadsheet that has no column for lost reports.
3Why does moving the advertising interval from 100 ms to 1.28 s improve a continuously advertising tag's life by roughly a factor of two rather than a factor of thirteen?›
Because the average current has two terms and only one of them scales with the interval. The packets themselves cost charge per event, so their contribution does fall by a factor of thirteen. But a continuously advertising device keeps its BLE controller alive between events — it is in a light-sleep or modem-sleep state at a floor in the region of a milliamp, not in deep sleep at 8 µA — and that floor does not change at all when you lengthen the interval.
Once the interval is long enough that the floor dominates, further lengthening buys almost nothing, and you converge on the floor's own battery life. The fix is not a longer interval; it is to stop being awake. Deep sleep between bursts moves the floor from milliamps to microamps, which is a factor of a hundred or more, and it is why Beacon's architecture is "wake, burst, sleep" rather than "advertise slowly".
4Beacon meets R4 (a report within two seconds of motion) in the lab and misses it badly in a customer's office. The tag firmware is identical. What changed, and how would you specify it away?›
The gateway's scanning changed. A BLE scanner is characterised by a scan window inside a scan interval, and their ratio is its duty cycle. A tag that transmits a three-packet burst is heard only if that burst overlaps a window on the channel the scanner happens to be listening to. At a 100 % duty cycle the first burst is caught and the latency is the tag's own wake time — tens of milliseconds. At a 20 % duty cycle roughly four bursts in five are missed, and since the next scheduled burst is 60 seconds away, the expected latency becomes minutes. Nothing about the tag caused it.
How to specify it away: make the gateway's scan window and scan interval a product requirement rather than an installation detail, and state the duty cycle needed to meet R4 (near-continuous scanning, which a mains-powered Raspberry Pi can afford). Then add the cheap belt-and-braces measure on the tag: on a motion wake, send more than one burst — for example three bursts spaced a few hundred milliseconds apart — so that a partially-listening gateway still has several chances inside the two-second window. That costs a few hundredths of a millicoulomb on motion events only, which is the right place to spend charge.