ESP32 BLE
Developer Guide
A comprehensive, step-by-step tutorial covering everything you need to build a production-ready BLE GATT Server and Client on ESP32 with ESP-IDF. From theory to bonded connections.
What is Bluetooth Low Energy?
Bluetooth Low Energy (BLE), introduced in Bluetooth 4.0, is a wireless communication protocol optimised for devices that must operate on tiny batteries for months or years. Unlike Classic Bluetooth, BLE uses short radio bursts rather than continuous streams, keeping current draw in the microamp range during idle periods.
ESP32 (all variants) includes a dual-mode Bluetooth radio. ESP-IDF exposes BLE through the Bluedroid stack (default) or, on newer chips, through the lighter NimBLE stack. This guide focuses on Bluedroid, which closely mirrors the Bluetooth SIG specification.
Low Energy
Designed for duty-cycled operation. A coin cell can last 1โ5 years depending on connection interval.
2.4 GHz ISM
Uses 40 ร 2 MHz channels; 3 advertising channels and 37 data channels with frequency hopping.
Range
Typically 10โ100 m line-of-sight. BLE Long Range (Coded PHY) extends to 300โ400 m.
Roles
Peripheral advertises and acts as server. Central scans, connects, and acts as client.
๐ ESP-IDF BLE Code Generator Link
Core Concepts: GAP, GATT, Services & Characteristics
GAP โ Generic Access Profile
GAP controls how devices advertise themselves, discover each other, and establish connections. A device in the Peripheral role broadcasts advertising packets every N milliseconds. A Central scans these packets, optionally filters by device name or UUID, and initiates a connection.
Shorter intervals (e.g. 20 ms) make the device discoverable faster but consume more power. For IoT sensors, 500โ1000 ms is a common balance. Minimum is 20 ms, maximum is 10.24 s.
GATT โ Generic Attribute Profile
GATT defines how data is structured, read, written, and notified over a BLE connection. All application data exchange happens through GATT. GATT uses a client/server model:
- GATT Server โ holds a database of attributes (your ESP32 sensor node).
- GATT Client โ reads/writes attributes on the server (your phone app or another ESP32).
The GATT Hierarchy
UUIDs
Every service, characteristic, and descriptor is identified by a UUID (Universally Unique Identifier). Bluetooth SIG defines 16-bit UUIDs for standard services (e.g. 0x180F = Battery Service). Custom vendor services use full 128-bit UUIDs.
16-bit UUIDs are shorthand โ they are actually 128-bit with the Bluetooth Base UUID 0000XXXX-0000-1000-8000-00805F9B34FB. Use 16-bit for standard SIG-defined services, 128-bit for anything custom.
Handles
In the actual ATT (Attribute Protocol) layer, every attribute is referenced by a 16-bit handle โ a sequential number assigned when services are registered. The handle is what the protocol actually uses over the air; UUIDs are looked up in the attribute table.
ESP-IDF BLE Stack Architecture
ESP-IDF's BLE stack (Bluedroid) is layered. Understanding the layers helps you know which API to call:
| Layer | API Prefix | Role |
|---|---|---|
| Application | โ | Your C code. Registers callbacks and calls API functions. |
| GATTS/GATTC | esp_ble_gatts_* / esp_ble_gattc_* | Create services, characteristics, read/write, notify. |
| GAP | esp_ble_gap_* | Advertising, scanning, connection parameters, security. |
| Bluedroid Core | esp_bluedroid_* | Stack lifecycle: init, enable, deinit. |
| Controller | esp_bt_controller_* | Hardware controller: init, enable, memory config. |
| ESP-IDF NVS | nvs_flash_* | Non-volatile storage โ required for bonding keys. |
Characteristic Properties Bitmask
| Property | Constant | Value | Description |
|---|---|---|---|
| READ | ESP_GATT_CHAR_PROP_BIT_READ | 0x02 | Client can read the characteristic value. |
| WRITE | ESP_GATT_CHAR_PROP_BIT_WRITE | 0x08 | Client can write with acknowledgement. |
| WRITE NR | ESP_GATT_CHAR_PROP_BIT_WRITE_NR | 0x04 | Write without response (faster, no ACK). |
| NOTIFY | ESP_GATT_CHAR_PROP_BIT_NOTIFY | 0x10 | Server can push updates; no ACK from client. |
| INDICATE | ESP_GATT_CHAR_PROP_BIT_INDICATE | 0x20 | Server pushes updates; client must ACK each one. |
| BROADCAST | ESP_GATT_CHAR_PROP_BIT_BROADCAST | 0x01 | Broadcast the characteristic in advertising packets. |
Creating a BLE Project in ESP-IDF
-
1
Install ESP-IDF v5.x
Follow the official guide at
docs.espressif.comto install the toolchain and set up your environment. Source the export script:. $IDF_PATH/export.sh -
2
Copy an example as your base
Use the official GATT server example as a starting point. It demonstrates the full callback structure.
-
3
Set the target chip
Run
idf.py set-target esp32(oresp32s3,esp32c3, etc.) before configuring. -
4
Configure via menuconfig
Run
idf.py menuconfigto enable the BLE stack and tune parameters. -
5
Build and flash
idf.py build flash monitorโ compiles, flashes to chip, and opens serial monitor.
Minimal project directory structure
filesystemmy_ble_project/ โโโ CMakeLists.txt โ top-level cmake โโโ sdkconfig โ generated by menuconfig โโโ main/ โ โโโ CMakeLists.txt โ component cmake โ โโโ main.c โ app_main() entry point โ โโโ gatts_demo.c โ GATT server logic โ โโโ gattc_demo.c โ GATT client logic (optional) โโโ components/ โ optional custom components
top-level CMakeLists.txt
cmakecmake_minimum_required(VERSION 3.16) include($ENV{IDF_PATH}/tools/cmake/project.cmake) project(my_ble_project)
main/CMakeLists.txt
cmakeidf_component_register( SRCS "main.c" "gatts_demo.c" INCLUDE_DIRS "." )
GATT Server โ Architecture & Initialisation
A GATT Server on ESP32 consists of:
- One or more Application Profiles โ each has a unique app ID and its own callback.
- Each profile registers Services, which contain Characteristics and Descriptors.
- ESP-IDF uses an event-driven model โ you register a global callback and a per-profile callback.
Initialisation sequence
c โ main.c#include "nvs_flash.h" #include "esp_bt.h" #include "esp_gap_ble_api.h" #include "esp_gatts_api.h" #include "esp_bt_main.h" #include "esp_gatt_common_api.h" void app_main(void) { // 1. Init NVS (required for bonding key storage) esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK(ret); // 2. Release Classic BT memory (BLE-only project) ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT)); // 3. Initialise and enable BT controller esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_bt_controller_init(&bt_cfg)); ESP_ERROR_CHECK(esp_bt_controller_enable(ESP_BT_MODE_BLE)); // 4. Initialise and enable Bluedroid stack ESP_ERROR_CHECK(esp_bluedroid_init()); ESP_ERROR_CHECK(esp_bluedroid_enable()); // 5. Register GATTS and GAP callbacks ESP_ERROR_CHECK(esp_ble_gatts_register_callback(gatts_event_handler)); ESP_ERROR_CHECK(esp_ble_gap_register_callback(gap_event_handler)); // 6. Register application profile (app_id = 0) ESP_ERROR_CHECK(esp_ble_gatts_app_register(PROFILE_APP_ID)); // 7. Set MTU (optional โ default 23, max 517) esp_ble_gatt_set_local_mtu(500); }
MTU (Maximum Transmission Unit) is the largest payload per packet. Default is 23 bytes (20 bytes usable). Call esp_ble_gatt_set_local_mtu(500) early to allow the client to negotiate a larger MTU for faster bulk transfers.
GATTS Events Reference
Your gatts_event_handler receives these events. Handle them in a switch statement:
| Event | When it fires | What to do |
|---|---|---|
ESP_GATTS_REG_EVT | App profile registered | Create the service (esp_ble_gatts_create_service), start advertising. |
ESP_GATTS_CREATE_EVT | Service table created | Start service (esp_ble_gatts_start_service), add characteristics. |
ESP_GATTS_ADD_CHAR_EVT | Characteristic added | Save the attribute handle, optionally add descriptors. |
ESP_GATTS_ADD_CHAR_DESCR_EVT | Descriptor added | Save descriptor handle. |
ESP_GATTS_CONNECT_EVT | Client connected | Save conn_id, update connection parameters if needed. |
ESP_GATTS_DISCONNECT_EVT | Client disconnected | Restart advertising. |
ESP_GATTS_READ_EVT | Client reads a characteristic | Respond with esp_ble_gatts_send_response. |
ESP_GATTS_WRITE_EVT | Client writes a characteristic | Process the data. Send response if need_rsp is true. |
ESP_GATTS_EXEC_WRITE_EVT | Long write execute | Assemble and confirm the write. |
ESP_GATTS_MTU_EVT | MTU negotiated | Record the negotiated MTU. |
ESP_GATTS_CONF_EVT | Indication confirmed | Called after client ACKs an indication. |
ESP_GATTS_START_EVT | Service started | Log success. |
ESP_GATTS_SET_ATTR_VAL_EVT | Attribute value set | Confirm value was written to ATT database. |
Event handler skeleton
cstatic void gatts_profile_event_handler( esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) { switch (event) { case ESP_GATTS_REG_EVT: /* Register succeeded โ create service here */ esp_ble_gatts_create_service(gatts_if, &gl_profile_tab[PROFILE_A_APP_ID].service_id, GATTS_NUM_HANDLE); /* Also start advertising */ esp_ble_gap_set_device_name(SAMPLE_DEVICE_NAME); esp_ble_gap_config_adv_data(&adv_data); break; case ESP_GATTS_CREATE_EVT: gl_profile_tab[PROFILE_A_APP_ID].service_handle = param->create.service_handle; esp_ble_gatts_start_service(param->create.service_handle); esp_ble_gatts_add_char( param->create.service_handle, &gatts_demo_char1_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_NOTIFY, &gatts_demo_char1_val, NULL); break; case ESP_GATTS_ADD_CHAR_EVT: gl_profile_tab[PROFILE_A_APP_ID].char_handle = param->add_char.attr_handle; /* Add CCCD descriptor to enable notifications */ esp_ble_gatts_add_char_descr( gl_profile_tab[PROFILE_A_APP_ID].service_handle, ¬ify_descr_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, NULL, NULL); break; case ESP_GATTS_READ_EVT: handle_read_event(gatts_if, param); break; case ESP_GATTS_WRITE_EVT: handle_write_event(gatts_if, param); break; case ESP_GATTS_CONNECT_EVT: gl_profile_tab[PROFILE_A_APP_ID].conn_id = param->connect.conn_id; break; case ESP_GATTS_DISCONNECT_EVT: esp_ble_gap_start_advertising(&adv_params); break; default: break; } }
Step-by-Step: Adding a Service
1 โ Define your service UUID
c/* 16-bit SIG-standard service UUID (Battery Service) */ #define GATTS_SERVICE_UUID_BATTERY 0x180F /* OR โ custom 128-bit UUID for your own service */ static uint8_t service_uuid128[16] = { /* LSB first (little-endian) */ 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0x9A };
2 โ Define the service ID structure
cstatic esp_gatt_srvc_id_t battery_service_id = { .id = { .uuid = { .len = ESP_UUID_LEN_16, .uuid = { .uuid16 = GATTS_SERVICE_UUID_BATTERY }, }, .inst_id = 0, /* instance ID (0 for first instance) */ }, .is_primary = true, /* primary vs secondary service */ };
3 โ Calculate and pass the number of handles
Each attribute (service declaration, characteristic declaration, characteristic value, and each descriptor) needs one handle. Formula: 1 (service) + 2 ร N_characteristics + N_descriptors. Example: 1 service + 2 characteristics + 2 CCCDs = 1 + 4 + 2 = 7 handles. Always add a safety buffer (e.g. +2).
c#define GATTS_NUM_HANDLE_BATTERY 8 /* 1 svc + 2 chars + 2 CCCDs + 2 user descs + 1 buffer */ /* Called inside ESP_GATTS_REG_EVT: */ esp_ble_gatts_create_service( gatts_if, &battery_service_id, GATTS_NUM_HANDLE_BATTERY );
4 โ Start the service
c/* Called inside ESP_GATTS_CREATE_EVT: */ uint16_t service_handle = param->create.service_handle; esp_ble_gatts_start_service(service_handle);
Step-by-Step: Adding Characteristics
Define the characteristic UUID and initial value
c#define GATTS_CHAR_UUID_BATTERY_LEVEL 0x2A19 static esp_gatt_char_prop_t a_property = ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_NOTIFY; static uint8_t char1_str[] = { 0x64 }; /* initial value: 100 (%) */ static esp_attr_value_t gatts_char_val = { .attr_max_len = 1, .attr_len = sizeof(char1_str), .attr_value = char1_str, }; static esp_bt_uuid_t char_uuid = { .len = ESP_UUID_LEN_16, .uuid = { .uuid16 = GATTS_CHAR_UUID_BATTERY_LEVEL }, };
Add the characteristic to the service
c/* Called inside ESP_GATTS_CREATE_EVT (after esp_ble_gatts_start_service) */ esp_ble_gatts_add_char( service_handle, /* from ESP_GATTS_CREATE_EVT */ &char_uuid, /* characteristic UUID */ ESP_GATT_PERM_READ, /* ATT permission: who can access */ a_property, /* GATT property: what operations */ &gatts_char_val, /* initial value (or NULL) */ NULL /* auto-response control (NULL = manual) */ );
Permission (ESP_GATT_PERM_*) controls the ATT-layer access (READ, WRITE, READ_ENCRYPTED, etc.). Property (ESP_GATT_CHAR_PROP_BIT_*) is what's advertised in the characteristic declaration to the GATT client. Set permissions at least as permissive as what you advertise in properties.
Permission constants quick reference
| Constant | Meaning |
|---|---|
ESP_GATT_PERM_READ | Read allowed (unencrypted) |
ESP_GATT_PERM_READ_ENCRYPTED | Read allowed only when link is encrypted |
ESP_GATT_PERM_READ_ENC_MITM | Read allowed when encrypted + authenticated |
ESP_GATT_PERM_WRITE | Write allowed (unencrypted) |
ESP_GATT_PERM_WRITE_ENCRYPTED | Write allowed only when link is encrypted |
ESP_GATT_PERM_WRITE_ENC_MITM | Write allowed when encrypted + authenticated |
Save the attribute handle
cuint16_t char_handle; /* store globally */ /* Inside ESP_GATTS_ADD_CHAR_EVT: */ case ESP_GATTS_ADD_CHAR_EVT: if (param->add_char.status == ESP_GATT_OK) { char_handle = param->add_char.attr_handle; ESP_LOGI(TAG, "Characteristic added, handle: 0x%04x", char_handle); } break;
Implementing Read, Write, Notify & Indicate
READ โ Responding to a client read
When a client reads your characteristic, ESP_GATTS_READ_EVT fires. You must call esp_ble_gatts_send_response unless you set auto_rsp when adding the characteristic.
ccase ESP_GATTS_READ_EVT: { ESP_LOGI(TAG, "READ handle=%d, conn=%d, trans=%d", param->read.handle, param->read.conn_id, param->read.trans_id); esp_gatt_rsp_t rsp; memset(&rsp, 0, sizeof(esp_gatt_rsp_t)); rsp.attr_value.handle = param->read.handle; /* Fill in your actual data */ rsp.attr_value.len = 1; rsp.attr_value.value[0] = get_battery_level(); /* your function */ esp_ble_gatts_send_response( gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &rsp); break; }
Pass an esp_attr_control_t with auto_rsp = ESP_GATT_AUTO_RSP to esp_ble_gatts_add_char to let the BLE stack reply automatically with the stored attribute value. Use manual response (ESP_GATT_RSP_BY_APP) when you need to return live/computed data.
WRITE โ Handling a client write
ccase ESP_GATTS_WRITE_EVT: { ESP_LOGI(TAG, "WRITE handle=%d len=%d, is_prep=%d need_rsp=%d", param->write.handle, param->write.len, param->write.is_prep, param->write.need_rsp); if (!param->write.is_prep) { /* Normal write โ process immediately */ handle_write_data(param->write.value, param->write.len); if (param->write.need_rsp) { esp_ble_gatts_send_response( gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, NULL); } } else { /* Prepared write (long write) โ buffer it */ prepare_write_env_cb(&prepare_write_env, gatts_if, param); } break; }
NOTIFY โ Server pushes data to client
Notifications are sent from your code whenever data changes. The client does not ACK them. Notifications only reach the client if they have enabled notifications via the CCCD descriptor.
cuint8_t notify_data[4] = { 0x01, 0x02, 0x03, 0x04 }; esp_ble_gatts_send_indicate( gatts_if, conn_id, /* saved from ESP_GATTS_CONNECT_EVT */ char_handle, /* attribute handle */ sizeof(notify_data), notify_data, false /* false = NOTIFY (no ACK), true = INDICATE (ACK required) */ );
INDICATE โ Same API, with acknowledgement
cesp_ble_gatts_send_indicate( gatts_if, conn_id, char_handle, sizeof(notify_data), notify_data, true /* โ true = INDICATION. Wait for ESP_GATTS_CONF_EVT before sending next */ ); /* ESP_GATTS_CONF_EVT fires when client sends the ACK */ case ESP_GATTS_CONF_EVT: if (param->conf.status != ESP_GATT_OK) { ESP_LOGE(TAG, "Indication failed, status=%d", param->conf.status); } break;
You must wait for ESP_GATTS_CONF_EVT before sending another indication. Sending a second indication before the first is confirmed will result in an error. Use a flag or semaphore.
User Description Descriptor (0x2901)
The Characteristic User Description descriptor (UUID 0x2901) lets you attach a human-readable UTF-8 string to any characteristic. Phone apps and BLE debuggers will display this string next to the characteristic.
cstatic esp_bt_uuid_t user_descr_uuid = { .len = ESP_UUID_LEN_16, .uuid = { .uuid16 = ESP_GATT_UUID_CHAR_DESCRIPTION }, /* 0x2901 */ }; static uint8_t user_desc[] = "Battery Level (%)"; static esp_attr_value_t user_descr_val = { .attr_max_len = sizeof(user_desc), .attr_len = sizeof(user_desc) - 1, /* exclude null terminator */ .attr_value = user_desc, }; /* Add inside ESP_GATTS_ADD_CHAR_EVT after saving char_handle: */ esp_ble_gatts_add_char_descr( service_handle, &user_descr_uuid, ESP_GATT_PERM_READ, /* read-only */ &user_descr_val, NULL );
CCCD โ Client Characteristic Configuration Descriptor (0x2902)
The CCCD is a 2-byte descriptor that the client writes to enable notifications or indications. Without a CCCD, the client cannot turn on notifications even if the characteristic has the NOTIFY property.
- Client writes
0x0001to enable Notifications. - Client writes
0x0002to enable Indications. - Client writes
0x0000to disable both.
Adding the CCCD
cstatic esp_bt_uuid_t notify_descr_uuid = { .len = ESP_UUID_LEN_16, .uuid = { .uuid16 = ESP_GATT_UUID_CHAR_CLIENT_CONFIG }, /* 0x2902 */ }; static uint8_t notify_ccc[2] = { 0x00, 0x00 }; /* initially disabled */ static esp_attr_value_t notify_ccc_val = { .attr_max_len = 2, .attr_len = 2, .attr_value = notify_ccc, }; /* Add after the characteristic: */ esp_ble_gatts_add_char_descr( service_handle, ¬ify_descr_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, ¬ify_ccc_val, NULL );
Detecting when the client enables notifications
cstatic bool notify_enabled = false; case ESP_GATTS_WRITE_EVT: if (param->write.handle == cccd_handle && param->write.len == 2) { uint16_t descr_value = (param->write.value[1] << 8) | param->write.value[0]; if (descr_value == 0x0001) { notify_enabled = true; ESP_LOGI(TAG, "Notifications ENABLED"); } else if (descr_value == 0x0002) { notify_enabled = true; ESP_LOGI(TAG, "Indications ENABLED"); } else if (descr_value == 0x0000) { notify_enabled = false; ESP_LOGI(TAG, "Notify/Indicate DISABLED"); } } break;
Complete GATT Server โ Putting It All Together
Below is a condensed but complete GATT server example: one service with a readable/writable/notifiable characteristic, a CCCD, and a user description. The advertising packet includes the service UUID so clients can filter by it.
c โ gatts_demo.c (condensed)#include <string.h> #include "esp_log.h" #include "esp_bt.h" #include "esp_gap_ble_api.h" #include "esp_gatts_api.h" #include "esp_bt_main.h" #define TAG "GATTS_DEMO" #define DEVICE_NAME "ESP32_BLE" #define SVC_UUID 0xFF00 #define CHAR_UUID 0xFF01 #define NUM_HANDLES 8 #define APP_ID 0 static uint16_t svc_handle, char_handle, cccd_handle, conn_id_g = 0xFFFF; static esp_gatt_if_t gatts_if_g; static bool notify_en = false; /* Advertising data โ include SVC UUID for filtering */ static uint8_t adv_service_uuid128[4] = { 0x00, 0xFF, 0x00, 0xFF }; static esp_ble_adv_data_t adv_data = { .set_scan_rsp = false, .include_name = true, .include_txpower = false, .min_interval = 0x0006, .max_interval = 0x0010, .appearance = 0, .manufacturer_len = 0, .p_manufacturer_data = NULL, .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = sizeof(adv_service_uuid128), .p_service_uuid = adv_service_uuid128, .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT), }; static esp_ble_adv_params_t adv_params = { .adv_int_min = 0x20, .adv_int_max = 0x40, .adv_type = ADV_TYPE_IND, .own_addr_type = BLE_ADDR_TYPE_PUBLIC, .channel_map = ADV_CHNL_ALL, .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { if (event == ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT) esp_ble_gap_start_advertising(&adv_params); } static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) { switch(event) { case ESP_GATTS_REG_EVT: { gatts_if_g = gatts_if; esp_ble_gap_set_device_name(DEVICE_NAME); esp_ble_gap_config_adv_data(&adv_data); esp_gatt_srvc_id_t svc_id = { .id = { .uuid = { .len = ESP_UUID_LEN_16, .uuid = { .uuid16 = SVC_UUID } }, .inst_id = 0 }, .is_primary = true }; esp_ble_gatts_create_service(gatts_if, &svc_id, NUM_HANDLES); break; } case ESP_GATTS_CREATE_EVT: { svc_handle = param->create.service_handle; esp_ble_gatts_start_service(svc_handle); esp_bt_uuid_t char_uuid = { .len = ESP_UUID_LEN_16, .uuid = { .uuid16 = CHAR_UUID } }; uint8_t val[] = { 0x00 }; esp_attr_value_t char_val = { .attr_max_len=20, .attr_len=1, .attr_value=val }; esp_ble_gatts_add_char(svc_handle, &char_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_NOTIFY, &char_val, NULL); break; } case ESP_GATTS_ADD_CHAR_EVT: { char_handle = param->add_char.attr_handle; esp_bt_uuid_t cccd_uuid = { .len = ESP_UUID_LEN_16, .uuid = { .uuid16 = ESP_GATT_UUID_CHAR_CLIENT_CONFIG } }; uint8_t ccc[] = { 0x00, 0x00 }; esp_attr_value_t ccc_val = { .attr_max_len=2, .attr_len=2, .attr_value=ccc }; esp_ble_gatts_add_char_descr(svc_handle, &cccd_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, &ccc_val, NULL); break; } case ESP_GATTS_ADD_CHAR_DESCR_EVT: cccd_handle = param->add_char_descr.attr_handle; break; case ESP_GATTS_CONNECT_EVT: conn_id_g = param->connect.conn_id; break; case ESP_GATTS_DISCONNECT_EVT: conn_id_g = 0xFFFF; notify_en = false; esp_ble_gap_start_advertising(&adv_params); break; case ESP_GATTS_READ_EVT: { esp_gatt_rsp_t rsp; memset(&rsp, 0, sizeof(rsp)); rsp.attr_value.handle = param->read.handle; rsp.attr_value.len = 1; rsp.attr_value.value[0] = 42; /* replace with real data */ esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &rsp); break; } case ESP_GATTS_WRITE_EVT: if (param->write.handle == cccd_handle && param->write.len == 2) { notify_en = (param->write.value[0] == 0x01); } if (param->write.need_rsp) esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, NULL); break; default: break; } } /* Call this from a timer/task to push updates */ void ble_send_notify(uint8_t *data, uint16_t len) { if (notify_en && conn_id_g != 0xFFFF) esp_ble_gatts_send_indicate(gatts_if_g, conn_id_g, char_handle, len, data, false); }
GATT Client โ Overview
A GATT Client (Central role) scans for advertising packets, connects to a peripheral, discovers its services and characteristics, then reads/writes/subscribes to them. On ESP32 you use the esp_ble_gattc_* API.
Scan โ Filter โ Connect โ Discover services โ Find characteristic handle โ Read/Write/Register notify. Each step is triggered by an event from the previous step โ it's a state machine.
GATTC initialisation
c/* app_main (same BT init as server, then): */ ESP_ERROR_CHECK(esp_ble_gattc_register_callback(gattc_event_handler)); ESP_ERROR_CHECK(esp_ble_gap_register_callback(gap_event_handler)); ESP_ERROR_CHECK(esp_ble_gattc_app_register(PROFILE_A_APP_ID));
GATTC Events Reference
| Event | When it fires | What to do |
|---|---|---|
ESP_GATTC_REG_EVT | App profile registered | Start scanning (esp_ble_gap_start_scanning). |
ESP_GATTC_CONNECT_EVT | ACL connection established | Call esp_ble_gattc_open to start GATT connection. |
ESP_GATTC_OPEN_EVT | GATT connection opened | Check status, then call esp_ble_gattc_search_service. |
ESP_GATTC_SEARCH_RES_EVT | One service found | Filter by UUID, save service start/end handles. |
ESP_GATTC_SEARCH_CMPL_EVT | Service discovery done | Get characteristics: esp_ble_gattc_get_char_by_uuid. |
ESP_GATTC_REG_FOR_NOTIFY_EVT | Registered for notify | Write 0x0001 to CCCD: esp_ble_gattc_write_char_descr. |
ESP_GATTC_NOTIFY_EVT | Server sent notification/indication | Process param->notify.value. |
ESP_GATTC_READ_CHAR_EVT | Read completed | Read param->read.value. |
ESP_GATTC_WRITE_CHAR_EVT | Write completed | Check status. |
ESP_GATTC_DISCONNECT_EVT | Connection closed | Restart scan or reconnect. |
Client: Scan, Filter, and Connect
Start scanning in ESP_GATTC_REG_EVT
cstatic esp_ble_scan_params_t scan_params = { .scan_type = BLE_SCAN_TYPE_ACTIVE, .own_addr_type = BLE_ADDR_TYPE_PUBLIC, .scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL, .scan_interval = 0x50, .scan_window = 0x30, .scan_duplicate = BLE_SCAN_DUPLICATE_DISABLE, }; case ESP_GATTC_REG_EVT: esp_ble_gap_set_scan_params(&scan_params); break;
Filter scan results and connect in GAP callback
c#define TARGET_DEVICE_NAME "ESP32_BLE" case ESP_GAP_BLE_SCAN_RESULT_EVT: { if (param->scan_rst.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) { uint8_t *adv = param->scan_rst.ble_adv; uint8_t len = param->scan_rst.adv_data_len; uint8_t name_len = 0; uint8_t *name = esp_ble_resolve_adv_data(adv, ESP_BLE_AD_TYPE_NAME_CMPL, &name_len); if (name && name_len == strlen(TARGET_DEVICE_NAME) && strncmp((char *)name, TARGET_DEVICE_NAME, name_len) == 0) { ESP_LOGI(TAG, "Found target device, connecting..."); esp_ble_gap_stop_scanning(); esp_ble_gattc_open( gl_profile_tab[PROFILE_A_APP_ID].gattc_if, param->scan_rst.bda, param->scan_rst.ble_addr_type, true); } } break; }
Client: Discover Services & Characteristics
cstatic uint16_t svc_start_hdl, svc_end_hdl, char_hdl, cccd_hdl; case ESP_GATTC_OPEN_EVT: if (param->open.status == ESP_GATT_OK) { gl_profile_tab[PROFILE_A_APP_ID].conn_id = param->open.conn_id; esp_ble_gattc_search_service(gattc_if, param->open.conn_id, NULL); /* NULL = discover all services */ } break; case ESP_GATTC_SEARCH_RES_EVT: if (param->search_res.srvc_id.uuid.uuid.uuid16 == SVC_UUID) { svc_start_hdl = param->search_res.start_handle; svc_end_hdl = param->search_res.end_handle; } break; case ESP_GATTC_SEARCH_CMPL_EVT: { esp_bt_uuid_t char_uuid = { .len=ESP_UUID_LEN_16, .uuid={ .uuid16=CHAR_UUID } }; esp_gattc_char_elem_t char_elem; uint16_t count = 1; esp_ble_gattc_get_char_by_uuid(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, svc_start_hdl, svc_end_hdl, char_uuid, &char_elem, &count); if (count > 0) { char_hdl = char_elem.char_handle; ESP_LOGI(TAG, "Characteristic found, handle 0x%04x", char_hdl); /* Now find the CCCD */ esp_bt_uuid_t cccd_uuid = { .len=ESP_UUID_LEN_16, .uuid={ .uuid16=ESP_GATT_UUID_CHAR_CLIENT_CONFIG } }; esp_gattc_descr_elem_t descr_elem; uint16_t dcnt = 1; esp_ble_gattc_get_descr_by_char_handle(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, char_hdl, cccd_uuid, &descr_elem, &dcnt); if (dcnt > 0) cccd_hdl = descr_elem.handle; } break; }
Client: Read and Write Characteristics
Reading a characteristic
cesp_ble_gattc_read_char( gattc_if, conn_id, char_hdl, ESP_GATT_AUTH_REQ_NONE /* or ESP_GATT_AUTH_REQ_NO_MITM for encrypted */ ); case ESP_GATTC_READ_CHAR_EVT: if (param->read.status == ESP_GATT_OK) { ESP_LOGI(TAG, "Read value len=%d", param->read.value_len); for (int i=0; i<param->read.value_len; i++) ESP_LOGI(TAG, " [%d]: 0x%02X", i, param->read.value[i]); } break;
Writing a characteristic
cuint8_t write_data[] = { 0x01, 0x02, 0x03 }; esp_ble_gattc_write_char( gattc_if, conn_id, char_hdl, sizeof(write_data), write_data, ESP_GATT_WRITE_TYPE_RSP, /* RSP = with acknowledgement */ ESP_GATT_AUTH_REQ_NONE );
Client: Enabling and Receiving Notifications
c/* Step 1: register for notify events */ esp_ble_gattc_register_for_notify(gattc_if, remote_bda, char_hdl); /* Step 2: in ESP_GATTC_REG_FOR_NOTIFY_EVT โ write 0x0001 to CCCD */ case ESP_GATTC_REG_FOR_NOTIFY_EVT: { uint8_t notify_en_val[2] = { 0x01, 0x00 }; esp_ble_gattc_write_char_descr( gattc_if, conn_id, cccd_hdl, sizeof(notify_en_val), notify_en_val, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE); break; } /* Step 3: receive notifications */ case ESP_GATTC_NOTIFY_EVT: ESP_LOGI(TAG, "Notification from handle 0x%04x, len=%d", param->notify.handle, param->notify.value_len); for (int i=0; i<param->notify.value_len; i++) ESP_LOGI(TAG, " [%d]: 0x%02X", i, param->notify.value[i]); break;
Pairing, Bonding & BLE Security
BLE security operates in distinct phases. Understanding the terminology is essential before writing security code:
ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH.IO Capabilities โ Choosing the Right Mode
The pairing method depends on what input/output the device physically has. Both sides declare their IO capabilities and the Bluetooth spec determines which pairing method is used:
| Constant | Value | Device hasโฆ | Pairing method |
|---|---|---|---|
ESP_IO_CAP_NONE | 3 | No display, no keyboard | Just Works (no MITM protection) |
ESP_IO_CAP_OUT | 1 | Display only (no keyboard) | Passkey Display โ server shows 6-digit code, user enters on other device |
ESP_IO_CAP_IN | 2 | Keyboard only (no display) | Passkey Entry โ user types passkey shown on the other device |
ESP_IO_CAP_IO | 4 | Keyboard + display | Numeric Comparison (BLE SC) or Passkey Entry (Legacy) |
ESP_IO_CAP_KBDISP | 0 | Keyboard + display (combined) | Best available โ Numeric Comparison preferred |
Pairing method matrix
The Bluetooth spec combines the two sides' IO caps to select the association model:
| Initiator โ / Responder โ | NoInput/NoOutput | Display Only | Display+Keyboard | Keyboard Only |
|---|---|---|---|---|
| NoInput/NoOutput | Just Works | Just Works | Just Works | Just Works |
| Display Only | Just Works | Just Works | Passkey Entry | Passkey Entry |
| Display+Keyboard | Just Works | Passkey Entry | Num. Comparison | Passkey Entry |
| Keyboard Only | Just Works | Passkey Entry | Passkey Entry | Passkey Entry |
For a headless sensor (no display, no keyboard) use ESP_IO_CAP_NONE. This results in "Just Works" pairing โ no user interaction, but also no MITM protection. For higher security, use ESP_IO_CAP_OUT with a display (show passkey) or ESP_IO_CAP_IN with a button (fixed passkey entry).
Security Modes & Levels
BLE defines Security Modes and within them Levels of protection that a characteristic can require:
| Mode | Level | Requirement |
|---|---|---|
| Mode 1 | Level 1 | No security (no encryption, no authentication) |
| Mode 1 | Level 2 | Unauthenticated pairing with encryption (Just Works) |
| Mode 1 | Level 3 | Authenticated pairing with encryption (MITM protected) |
| Mode 1 | Level 4 | Authenticated LE SC pairing with encryption (strongest) |
| Mode 2 | Level 1 | Unauthenticated pairing with data signing |
| Mode 2 | Level 2 | Authenticated pairing with data signing |
In ESP-IDF, you enforce a security mode by using ESP_GATT_PERM_READ_ENCRYPTED / ESP_GATT_PERM_WRITE_ENCRYPTED (Level 2) or ESP_GATT_PERM_READ_ENC_MITM / ESP_GATT_PERM_WRITE_ENC_MITM (Level 3) on characteristics.
Implementing Pairing & Bonding in Code
1 โ Configure security parameters
cvoid setup_ble_security(void) { /* Authentication requirements */ esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND; /* * ESP_LE_AUTH_NO_BOND โ no bonding, no MITM * ESP_LE_AUTH_BOND โ bond, no MITM (Just Works) * ESP_LE_AUTH_REQ_MITM โ no bond, MITM (passkey) * ESP_LE_AUTH_REQ_SC_ONLY โ LE SC, no bond * ESP_LE_AUTH_REQ_SC_BOND โ LE SC + bond * ESP_LE_AUTH_REQ_SC_MITM โ LE SC + MITM, no bond * ESP_LE_AUTH_REQ_SC_MITM_BOND โ LE SC + MITM + bond (strongest) */ esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t)); /* IO capability of this device */ esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE; /* headless device */ esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); /* Key distribution โ what keys each side sends */ uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t)); /* Maximum bonded devices to store */ uint8_t max_bonds = 4; esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_BOND_DEV_NUM, &max_bonds, sizeof(uint8_t)); /* Only accept specified security auth */ uint8_t only_accept = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE; esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &only_accept, sizeof(uint8_t)); }
2 โ Handle security events in GAP callback
ccase ESP_GAP_BLE_SEC_REQ_EVT: /* Peer is requesting pairing โ accept it */ esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true); break; case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: /* Display the 6-digit passkey on your display/UART */ ESP_LOGI(TAG, "Passkey to enter on peer: %06d", param->ble_security.key_notif.passkey); break; case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* User has entered the passkey shown on the peer โ confirm it */ esp_ble_passkey_reply( param->ble_security.ble_req.bd_addr, true, 123456 /* replace with user-entered value */ ); break; case ESP_GAP_BLE_NC_REQ_EVT: /* Numeric Comparison (LE SC): show number, user confirms yes/no */ ESP_LOGI(TAG, "Numeric comparison: %06d", param->ble_security.key_notif.passkey); esp_ble_confirm_reply( param->ble_security.ble_req.bd_addr, true /* true = confirmed; false = rejected */ ); break; case ESP_GAP_BLE_AUTH_CMPL_EVT: if (param->ble_security.auth_cmpl.success) { ESP_LOGI(TAG, "Pairing SUCCESS! Auth mode: 0x%02x", param->ble_security.auth_cmpl.auth_mode); } else { ESP_LOGE(TAG, "Pairing FAILED! Reason: 0x%02x", param->ble_security.auth_cmpl.fail_reason); } break;
3 โ Initiate security from the server side (optional)
c/* Called when a device connects but hasn't paired yet */ case ESP_GATTS_CONNECT_EVT: conn_id_g = param->connect.conn_id; /* Ask the stack to start the security/pairing procedure */ esp_ble_set_encryption(param->connect.remote_bda, ESP_BLE_SEC_ENCRYPT_MITM);
Bond Management โ Listing and Removing Bonded Devices
cvoid list_bonded_devices(void) { int dev_num = esp_ble_get_bond_device_num(); ESP_LOGI(TAG, "Bonded devices: %d", dev_num); esp_ble_bond_dev_t *dev_list = (esp_ble_bond_dev_t *)malloc(sizeof(esp_ble_bond_dev_t) * dev_num); esp_ble_get_bond_device_list(&dev_num, dev_list); for (int i = 0; i < dev_num; i++) { ESP_LOGI(TAG, " [%d]: %02x:%02x:%02x:%02x:%02x:%02x", i, dev_list[i].bd_addr[0], dev_list[i].bd_addr[1], dev_list[i].bd_addr[2], dev_list[i].bd_addr[3], dev_list[i].bd_addr[4], dev_list[i].bd_addr[5]); } free(dev_list); } /* Remove a specific bonded device */ void remove_bond_device(esp_bd_addr_t bda) { esp_ble_remove_bond_device(bda); ESP_LOGI(TAG, "Bond removed"); } /* Remove ALL bonded devices (factory reset BLE) */ void remove_all_bonds(void) { int dev_num = esp_ble_get_bond_device_num(); esp_ble_bond_dev_t *dev_list = (esp_ble_bond_dev_t *)malloc(sizeof(esp_ble_bond_dev_t) * dev_num); esp_ble_get_bond_device_list(&dev_num, dev_list); for (int i = 0; i < dev_num; i++) esp_ble_remove_bond_device(dev_list[i].bd_addr); free(dev_list); ESP_LOGI(TAG, "All bonds removed"); }
Bond keys are stored in NVS. Calling nvs_flash_erase() removes all bond data โ only do this intentionally during development or factory reset flows.
Reconnecting to a bonded device
When a bonded central reconnects, the stack automatically uses the stored LTK to encrypt the link without user interaction. The server should call esp_ble_set_encryption again after ESP_GATTS_CONNECT_EVT to ensure the link re-encrypts using the stored bond.
Troubleshooting Common Issues
| Symptom | Likely cause | Fix |
|---|---|---|
| Device not visible in scanner | Advertising not started, or wrong channel | Check ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT fires before esp_ble_gap_start_advertising. |
ESP_ERR_INVALID_STATE on init | NVS not initialised | Always call nvs_flash_init() before BT init. |
| No notifications received | CCCD not written | Ensure client writes 0x0001 to CCCD. Check notify_en flag on server. |
| Characteristic handle is 0 | Handle not saved in event | Save param->add_char.attr_handle in ESP_GATTS_ADD_CHAR_EVT. |
| Pairing fails immediately | Security param mismatch | Ensure both sides agree on IO caps. Try ESP_IO_CAP_NONE + ESP_LE_AUTH_BOND first. |
| Heap exhausted / crash | BLE stack + app too large | Use esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT). Use BLE-only controller mode. |
| Long write not working | ESP_GATTS_EXEC_WRITE_EVT not handled | Implement execute_write_event_env to reassemble and confirm the write. |
Indication error 0x0a | Sent second indication before ACK | Wait for ESP_GATTS_CONF_EVT before sending the next indication. |
| MTU too small | Never called esp_ble_gatt_set_local_mtu | Call it early in init with value up to 517. |
| Device appears twice in bond list | IRK not exchanged (address changes) | Set ESP_BLE_ID_KEY_MASK in key distribution to exchange IRK. |
Glossary
| Term | Definition |
|---|---|
| ATT | Attribute Protocol โ low-level protocol for reading/writing attributes over a BLE connection. |
| Attribute | Any piece of data in the GATT database: service declaration, characteristic declaration, value, or descriptor. |
| BDA | Bluetooth Device Address โ 6-byte MAC-like address. Can be public, static random, resolvable private, or non-resolvable private. |
| BLE SC / LESC | LE Secure Connections โ BLE 4.2+ ECDH-based key exchange. Replaces legacy SMP for higher security. |
| CCCD | Client Characteristic Configuration Descriptor (UUID 0x2902) โ written by the client to enable notify (0x0001) or indicate (0x0002). |
| Central | GAP role that scans and initiates connections. Also the GATT Client role in practice. |
| Characteristic | A typed data value in a GATT service, with properties (read/write/notify) and an optional set of descriptors. |
| conn_id | Connection identifier โ a number assigned by the stack to each active connection. Required for most GATTS/GATTC API calls. |
| CSRK | Connection Signature Resolving Key โ used for data signing (Security Mode 2). |
| GAP | Generic Access Profile โ governs device discovery, advertising, and connection procedures. |
| gatts_if | GATTS interface identifier โ like a file descriptor for the GATT server instance. Passed to most GATTS API calls. |
| GATT | Generic Attribute Profile โ defines how data is organised and transferred over BLE. |
| Handle | 16-bit number referencing an attribute in the ATT database. Assigned sequentially when services are registered. |
| Indication | Server-initiated data push that requires a confirmation (ACK) from the client. More reliable than Notification. |
| IRK | Identity Resolving Key โ allows resolution of a peer's randomised private address back to its real identity. |
| Just Works | Pairing method with no user interaction. Encrypts the link but provides no MITM protection. |
| LTK | Long-Term Key โ the main encryption key. Stored during bonding for re-encryption on subsequent connections. |
| MITM | Man-in-the-Middle. BLE security level 3+ is MITM-protected, meaning a passive eavesdropper cannot inject data. |
| MTU | Maximum Transmission Unit โ max payload per ATT packet. Default 23 bytes; can be negotiated up to 517 bytes. |
| Notification | Server-initiated data push with no ACK from client. Fast and low-overhead but delivery not guaranteed. |
| NVS | Non-Volatile Storage โ ESP-IDF key-value store in flash. Used by Bluedroid to persist bonding keys. |
| OOB | Out-of-Band โ pairing using a channel other than BLE (e.g. NFC, QR code) to exchange keys. |
| Passkey | 6-digit number used to confirm pairing identity. One device displays it, the other inputs it. |
| Peripheral | GAP role that advertises and accepts connections. Also the GATT Server role in practice. |
| Profile | A collection of services designed to fulfil a specific use case (e.g. Heart Rate Profile). |
| Service | A logical container for related characteristics, identified by a UUID. |
| SMP | Security Manager Protocol โ the pairing and key exchange protocol in BLE. |
| UUID | Universally Unique Identifier โ 16-bit (SIG-defined) or 128-bit (custom) identifier for services, characteristics, and descriptors. |
Official ESP-IDF BLE examples: $IDF_PATH/examples/bluetooth/bluedroid/ble/
Bluetooth SIG assigned numbers: https://www.bluetooth.com/specifications/assigned-numbers/
ESP-IDF API docs: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/bluetooth/