Create a Custom BLE GATT Service on nRF52
Define a custom 128-bit GATT service on nRF52 with Zephyr: characteristic properties, read and write callbacks, notifications through the CCC and MTU limits.

After a phone connects to a BLE peripheral, everything it can read or write is organised by GATT, the Generic Attribute Profile. A service groups related characteristics, and a characteristic holds a value with properties that say whether it can be read, written or notified. Standard services such as Battery or Heart Rate have 16-bit UUIDs assigned by the Bluetooth SIG, and anything else needs a custom service with a 128-bit UUID you generate. This post builds one on an nRF52840 with the Zephyr Bluetooth host in the nRF Connect SDK v2.9: a read characteristic, a write characteristic with validation and a notify characteristic that the phone can subscribe to. The attribute model comes from the Bluetooth Core Specification, volume 3, part G.
The attribute table
GATT is a table of attributes, each with a handle, a type UUID, permissions and a value. A characteristic is more than one attribute:
| Attribute | Type UUID | Holds |
|---|---|---|
| Service declaration | 0x2800 (primary service) | The service UUID |
| Characteristic declaration | 0x2803 | Properties, the value handle, the characteristic UUID |
| Characteristic value | the characteristic UUID | The data |
| Client Characteristic Configuration (CCC) descriptor | 0x2902 | Two bits: notifications and indications enabled by the client |
A characteristic that supports notifications needs the CCC descriptor, so that each client can switch them on. When you define a service in Zephyr, you list these in order, and the macros create the declarations for you.
UUIDs
Pick a base 128-bit UUID once and derive the rest by changing a few bytes. Generate it with uuidgen, not by hand. These constants are an example:
#pragma once
#include <stdint.h>
#include <zephyr/bluetooth/uuid.h>
#define LAB_UUID_BASE(x) BT_UUID_128_ENCODE(0x7a1c0000 + (x), 0x4d3b, 0x4e5a, 0x8f21, 0x2b6e91c4d5a7)
#define LAB_SERVICE_UUID LAB_UUID_BASE(0x0001)
#define LAB_TEMP_UUID LAB_UUID_BASE(0x0002)
#define LAB_LED_UUID LAB_UUID_BASE(0x0003)
#define LAB_COUNT_UUID LAB_UUID_BASE(0x0004)
void lab_set_temperature(int16_t centi);
void lab_count_tick(void);BT_UUID_128_ENCODE(w32, w1, w2, w3, w48) takes the five fields of the canonical UUID text form, 7a1c0001-4d3b-4e5a-8f21-2b6e91c4d5a7 and so on, and expands into the 16 bytes in the little-endian order the stack wants. The macro takes literal numbers, so the 0x7a1c0000 + (x) form works because the compiler folds it into a constant.
The service
The service has three characteristics: a temperature the phone can read and be notified about, an LED control the phone can write, and a counter it can read.
#include <zephyr/kernel.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/gatt.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/logging/log.h>
#include "lab_service.h"
LOG_MODULE_REGISTER(lab, LOG_LEVEL_INF);
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(DT_ALIAS(led0), gpios);
static struct bt_uuid_128 svc_uuid = BT_UUID_INIT_128(LAB_SERVICE_UUID);
static struct bt_uuid_128 temp_uuid = BT_UUID_INIT_128(LAB_TEMP_UUID);
static struct bt_uuid_128 led_uuid = BT_UUID_INIT_128(LAB_LED_UUID);
static struct bt_uuid_128 count_uuid = BT_UUID_INIT_128(LAB_COUNT_UUID);
static int16_t temp_centi = 2150;
static uint8_t led_state;
static uint32_t counter;
static bool temp_notify;
static ssize_t read_temp(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,
&temp_centi, sizeof(temp_centi));
}
static ssize_t read_count(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,
&counter, sizeof(counter));
}
static ssize_t write_led(struct bt_conn *conn, const struct bt_gatt_attr *attr,
const void *buf, uint16_t len, uint16_t offset,
uint8_t flags)
{
if (offset != 0) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
if (len != 1) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
}
uint8_t value = *(const uint8_t *)buf;
if (value > 1) {
return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
}
led_state = value;
gpio_pin_set_dt(&led, led_state);
LOG_INF("led set to %u", led_state);
return len;
}
static void temp_ccc_changed(const struct bt_gatt_attr *attr, uint16_t value)
{
temp_notify = (value == BT_GATT_CCC_NOTIFY);
LOG_INF("temperature notifications %s", temp_notify ? "on" : "off");
}
BT_GATT_SERVICE_DEFINE(lab_svc,
BT_GATT_PRIMARY_SERVICE(&svc_uuid),
BT_GATT_CHARACTERISTIC(&temp_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
BT_GATT_PERM_READ, read_temp, NULL, NULL),
BT_GATT_CCC(temp_ccc_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
BT_GATT_CHARACTERISTIC(&led_uuid.uuid,
BT_GATT_CHRC_WRITE,
BT_GATT_PERM_WRITE, NULL, write_led, NULL),
BT_GATT_CHARACTERISTIC(&count_uuid.uuid,
BT_GATT_CHRC_READ,
BT_GATT_PERM_READ, read_count, NULL, NULL),
);
void lab_set_temperature(int16_t centi)
{
temp_centi = centi;
if (temp_notify) {
bt_gatt_notify_uuid(NULL, &temp_uuid.uuid, lab_svc.attrs,
&temp_centi, sizeof(temp_centi));
}
}
void lab_count_tick(void)
{
counter++;
}Walk through the definitions. BT_GATT_CHARACTERISTIC takes the UUID, the property flags that go into the declaration, the permission flags that control access to the value, the read callback, the write callback and a user data pointer. Properties describe what the characteristic can do, and permissions describe what a connection is allowed to do, so a property of write with a permission requiring encryption means the write is refused on an unencrypted link. BT_GATT_CCC adds the descriptor right after the characteristic it belongs to, and the callback tells you when a client subscribes.
The write callback validates everything, because the bytes come from the air. It rejects a non-zero offset, a wrong length and a value outside 0 or 1 with the specific ATT error code the client sees. Returning len tells the stack the write was accepted in full. A characteristic with write permission and no validation is a classic source of bugs, since a client can send any length.
bt_gatt_notify_uuid finds the attribute by its UUID within the service's attribute array, so you do not have to count indexes. Passing NULL as the connection notifies every connected client that subscribed.
Starting the stack
Pull everything together with a connectable advertiser that includes the service UUID, so that a scanner can filter for it.
#include <zephyr/kernel.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/gap.h>
#include <zephyr/bluetooth/uuid.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/logging/log.h>
#include "lab_service.h"
LOG_MODULE_REGISTER(app, LOG_LEVEL_INF);
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(DT_ALIAS(led0), gpios);
static const struct bt_data ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA_BYTES(BT_DATA_UUID128_ALL, LAB_SERVICE_UUID),
};
static const struct bt_data sd[] = {
BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME,
sizeof(CONFIG_BT_DEVICE_NAME) - 1),
};
int main(void)
{
gpio_pin_configure_dt(&led, GPIO_OUTPUT_INACTIVE);
int err = bt_enable(NULL);
if (err) {
LOG_ERR("bt_enable failed (%d)", err);
return 0;
}
err = bt_le_adv_start(BT_LE_ADV_CONN, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));
if (err) {
LOG_ERR("advertising failed (%d)", err);
return 0;
}
LOG_INF("advertising");
int16_t t = 2150;
while (1) {
k_sleep(K_SECONDS(2));
t += 5;
lab_count_tick();
lab_set_temperature(t);
}
}The 128-bit UUID takes 16 bytes plus 2 of header, so the advertising data holds 3 bytes of flags and 18 bytes of UUID, 21 in all, and the name goes in the scan response where the 31-byte limit applies separately. Putting both in the primary packet would exceed it, which is why the structure is split. If your SDK version marks BT_LE_ADV_CONN as deprecated, use BT_LE_ADV_CONN_FAST_1, or build the parameters with BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE, ...) as the beacon post does.
CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_DEVICE_NAME="SC_Lab"
CONFIG_GPIO=y
CONFIG_LOG=yTesting from a phone
In the nRF Connect for Mobile app, scan, connect to SC_Lab and open the unknown service. You see three characteristics with their 128-bit UUIDs. Tap the read arrow on the temperature characteristic. The app shows the raw bytes and often tries to decode them:
Value: 0x6608The value 2150 is 0x0866, and the characteristic stores it little-endian, so the bytes on the air and in the app's hex view are 66 08. Subscribe to notifications, and the device log prints temperature notifications on and the value changes every two seconds. Write 01 to the LED characteristic and the LED turns on, with led set to 1 in the log. Write 05 and the app reports an error "value not allowed", the code returned by the validation.
MTU and long values
A characteristic value is limited by the ATT MTU, the largest packet the two sides agree on. The default is 23 bytes, which leaves 20 bytes of payload per notification after the 3-byte header. Larger payloads need a larger MTU, negotiated by the central after connecting, and the peripheral allows up to the limit in its Kconfig:
CONFIG_BT_L2CAP_TX_MTU=247
CONFIG_BT_BUF_ACL_RX_SIZE=251
CONFIG_BT_BUF_ACL_TX_SIZE=251With these settings, a central that asks for a 247-byte MTU gets it, and notifications can carry up to 244 bytes. For values bigger than one packet, reads use blob reads with an offset, which bt_gatt_attr_read handles by itself because it takes the offset argument.
Choosing properties
Pick the smallest set that does the job. Notify is for values the device pushes. Indicate is the same with an acknowledgement from the client, at the cost of waiting for each one. Write without response is for a fast stream of commands where a lost packet is acceptable, and write with response is for commands that must be confirmed. A characteristic that the phone reads once at connection and that rarely changes should not notify. An unneeded CCC costs a descriptor and a callback.
Security on a characteristic
Change BT_GATT_PERM_WRITE to BT_GATT_PERM_WRITE_ENCRYPT and the stack refuses the write on an unencrypted link with an "insufficient encryption" error, which makes a phone begin pairing. Add CONFIG_BT_SMP=y to enable the pairing machinery. A write characteristic that changes device behaviour, such as turning on a relay, should require encryption and, for a product, authenticated pairing.
When a custom service is the wrong choice
If a standard service fits, use it, because phones and libraries already know how to talk to it. The Battery Service, Device Information Service and Environmental Sensing Service cover common cases. Zephyr includes the Battery and Device Information services with a Kconfig switch each. For a large data transfer, GATT is slow and a stream-oriented design with L2CAP connection-oriented channels, or the Nordic UART Service for a quick serial pipe, may suit better.


