flowchart LR
subgraph C["Controller"]
LL["Link Layer"]
end
subgraph HT["Host task (nimble_port_run)"]
Q[("Event queue")]
H["NimBLE host<br/>GAP / GATT / ATT / SM"]
CB["App callbacks<br/>gap_event_cb()<br/>gatt_access_cb()"]
Q --> H --> CB
end
subgraph APP["App tasks"]
M["app_main / notify_task"]
end
LL -->|"HCI events"| Q
M -->|"ble_gatts_notify_custom() etc.<br/>(takes a lock internally)"| H
4 NimBLE, ESP-IDF’s BLE stack
4.1 Bluedroid and NimBLE
ESP-IDF contains two implementations of the BLE host (the GAP, GATT, ATT, SM and L2CAP of Chapter 2).
| Bluedroid | NimBLE | |
|---|---|---|
| Origin | Android’s Bluetooth stack | Apache Mynewt’s BLE stack |
| Supports | Bluetooth Classic + BLE | BLE only |
| Size | Large | Small (less flash and RAM) |
| API | esp_ble_gap_*, esp_ble_gatts_* (Espressif’s own wrappers) |
ble_gap_*, ble_gatts_* (close to the specification’s terms) |
The ESP32-C3 has no Bluetooth Classic, so there is almost no reason to choose Bluedroid. This hands-on uses NimBLE.
4.2 Enabling BLE in sdkconfig
Bluetooth in ESP-IDF is disabled by default. Write the following in sdkconfig.defaults (Steps 2–4).
CONFIG_IDF_TARGET="esp32c3"
# Bluetooth (NimBLE, BLE only)
CONFIG_BT_ENABLED=y
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_MAX_CONNECTIONS=1| Setting | Meaning |
|---|---|
CONFIG_BT_ENABLED |
Enable the Bluetooth component |
CONFIG_BT_NIMBLE_ENABLED |
Use NimBLE as the host (not Bluedroid) |
CONFIG_BT_NIMBLE_MAX_CONNECTIONS |
Number of simultaneous connections. If you accept only one, set it to 1 to save memory |
In idf.py menuconfig you can make the same settings under Component config → Bluetooth. Other items there include
- Component config → Bluetooth → NimBLE Options → Preferred MTU size (default 256)
- … → NimBLE Options → NimBLE Host task stack size (default 4096 bytes)
- … → NimBLE Options → Maximum number of bonds to save across reboots (default 3)
and so on.
sdkconfig.defaults is only used as the initial value for items not yet written in sdkconfig. If you build once without BLE as in Step 1, sdkconfig ends up with # CONFIG_BT_ENABLED is not set (= disabled) written in it. If you then add CONFIG_BT_ENABLED=y to sdkconfig.defaults, the value in sdkconfig takes precedence and BLE does not become enabled.
Fix: delete sdkconfig and rebuild (it is recreated from sdkconfig.defaults), or enable it directly with idf.py menuconfig. Each step of the sample does not include sdkconfig, so it is created correctly on the first build.
4.3 How NimBLE runs
4.3.1 The host task
The NimBLE host runs inside a dedicated FreeRTOS task (the host task). All events arriving from the controller (connected, data arrived…) are processed in this task, and the app’s callbacks (GAP events, GATT accesses) are also called inside this task.
gap_event_cb() and gatt_access_cb() are called inside the host task. If you vTaskDelay() or do heavy processing here, all BLE processing stops in the meantime (the next packet is not processed, pairing times out…). In callbacks, limit yourself to recording state, copying data and posting events, and do heavy processing in another task (Chapter 10).
On the other hand, host APIs such as ble_gatts_notify_custom() take a lock internally before processing, so it is fine to call them from another task. ESP-IDF’s blehr (heart-rate monitor) example also sends Notify from a FreeRTOS software timer callback.
4.3.2 Initialization order
The app_main() of an app using NimBLE takes roughly the following form.
sequenceDiagram participant A as app_main participant N as NimBLE participant H as Host task A->>A: nvs_flash_init() A->>N: nimble_port_init()<br/>(initialize controller + host) A->>N: set sync_cb / reset_cb / sm_* in ble_hs_cfg A->>N: ble_svc_gap_init() / ble_svc_gatt_init() A->>N: ble_gatts_count_cfg() / ble_gatts_add_svcs()<br/>(register your own services) A->>H: nimble_port_freertos_init(host_task)<br/>(start the host task) H->>H: nimble_port_run() H-->>H: synchronize with the controller H->>A: sync_cb() — only now can BLE be used A->>N: ble_gap_adv_start() (start advertising)
| Function | Role |
|---|---|
nvs_flash_init() |
Initialize non-volatile storage. Used to store radio (PHY) calibration data and bonding information (Chapter 9) |
nimble_port_init() |
Initialize the controller and host |
ble_hs_cfg |
Global variable holding the host’s configuration (callbacks, security). Set it before starting the host task |
ble_svc_gap_init() |
Register the standard GAP service (0x1800: device name etc.) |
ble_svc_gatt_init() |
Register the standard GATT service (0x1801: Service Changed) |
ble_gatts_count_cfg() |
Count your service definitions and tell the host how much memory is needed |
ble_gatts_add_svcs() |
Queue your service definitions for registration (they actually go into the attribute table after sync) |
nimble_port_freertos_init() |
Create the host task. nimble_port_run() is called inside the task |
sync_cb |
Called when the host and controller are synchronized. Start advertising from here |
reset_cb |
When the host is reset due to inconsistency with the controller etc. After a reset, sync_cb is called again |
Calling ble_gap_adv_start() at the end of app_main() fails because sync has not happened yet. Start advertising and obtain the address inside sync_cb.
4.3.3 GAP informs via events
Everything related to GAP — connections, disconnections, subscriptions, pairing and so on — arrives at a single callback as a struct ble_gap_event. Which callback it goes to is determined by the function passed to ble_gap_adv_start() (the callback of the advertisement that accepted the connection receives that connection’s events).
| Event | When |
|---|---|
BLE_GAP_EVENT_CONNECT |
Connected (or failed to connect: status != 0) |
BLE_GAP_EVENT_DISCONNECT |
Disconnected (reason in reason) |
BLE_GAP_EVENT_ADV_COMPLETE |
Advertising ended (timed out, etc.) |
BLE_GAP_EVENT_CONN_UPDATE |
Connection parameters changed |
BLE_GAP_EVENT_MTU |
MTU was decided |
BLE_GAP_EVENT_SUBSCRIBE |
A CCCD was written (subscribe/unsubscribe to Notify / Indicate) |
BLE_GAP_EVENT_ENC_CHANGE |
Encryption started or failed |
BLE_GAP_EVENT_PASSKEY_ACTION |
Pairing needs a passkey to be displayed or entered |
BLE_GAP_EVENT_REPEAT_PAIRING |
An already-bonded peer is trying to pair again |
4.4 mbuf: NimBLE’s packet buffer
NimBLE handles packet data in units called struct os_mbuf (memory buffers). An mbuf is a chain of fixed-size blocks, and long data spans several blocks.
| Function / macro | Use |
|---|---|
ble_hs_mbuf_from_flat(data, len) |
Create an mbuf from a plain array (used for sending Notify) |
os_mbuf_append(om, data, len) |
Append data to the end of an mbuf (used for Read responses) |
OS_MBUF_PKTLEN(om) |
Length of the whole mbuf chain |
ble_hs_mbuf_to_flat(om, buf, max, &len) |
Copy an mbuf into a plain array (used for receiving Write) |
The om passed to ble_gatts_notify_custom(conn, handle, om) is freed by NimBLE whether it succeeds or fails. The caller must not call os_mbuf_free_chain() (that would be a double free). Conversely, the ctxt->om received on Write belongs to the host, so it cannot be used after the callback returns. Copy the data you need into an array.
- Use NimBLE for BLE on the ESP32-C3. Enable it in
sdkconfig - Callbacks are called inside the host task. Don’t wait, don’t do heavy work
- BLE APIs can be used after
sync_cb - GAP occurrences arrive at a single callback as
BLE_GAP_EVENT_* - Data is passed in mbufs. NimBLE frees mbufs you send