IoT · Embedded Systems
BLE GATT Profile Design for Hardware Control: AtomBrick
GATT profile decisions made early constrain the protocol forever. Build a reviewed profile using UUID selection, characteristic properties, and descriptor design from a real motor controller.
- Published
- Reading
- 8 min
- Author
- Fidelis Uwem Joseph
Series · Part 2 of 4BLE & AtomBrick
- AtomBrick: ESP32 BLE Motor Controller to KMP Mobile App
- BLE GATT Profile Design for Hardware Control: AtomBrick
- ESP32 BLE Passkey Pairing, Bonding, and Encryption
- Kotlin Multiplatform BLE with Kable, Koin, and Compose
When you define a BLE GATT profile for the first time, it feels like boilerplate: pick some UUIDs, create a service, add characteristics. Those decisions define the protocol between your firmware and every app that ever connects to the device. AtomBrick went through one revision of this, and the mistakes are specific enough to be worth documenting.
Prerequisites
- Familiarity with the BLE GATT model: services, characteristics, descriptors, and properties
- An ESP32 with the Arduino BLE stack (
BLEDevice.h) - nRF Connect (iOS or Android) for verifying profile structure
Background
A GATT profile is a hierarchy: a peripheral exposes services, each containing characteristics, each optionally with descriptors. A characteristic is a typed value whose properties (READ, WRITE, WRITE_WITHOUT_RESPONSE, NOTIFY, INDICATE) declare what operations are allowed.
The Bluetooth SIG publishes a registry of 16-bit UUIDs for common data types. For custom hardware, you either define a custom 128-bit UUID or reuse an existing SIG UUID if the semantics are genuinely close.
Implementation
1. The AtomBrick GATT profile as shipped
Service: 0000180D-0000-1000-8000-00805F9B34FB (Heart Rate, repurposed)Motor 1: 00002A31-... READ | WRITE | NOTIFYMotor 2: 00002A32-... READ | WRITE | NOTIFYMotor 3: 00002A33-... READ | WRITE | NOTIFYMotor 4: 00002A34-... READ | WRITE | NOTIFYMotor 5: 00002A35-... READ | WRITE | NOTIFYName: 00002A36-... READ | WRITESix characteristics in one service. Each motor characteristic carries a BLE2902 descriptor (CCCD, UUID 0x2902) to enable NOTIFY subscriptions.
2. UUID selection: what to do instead
Generate a custom base UUID with uuidgen and derive each characteristic from it:
Service: A1B2C3D4-0000-1000-8000-00805F9B34FBMotor 1: A1B2C3D4-0001-1000-8000-00805F9B34FBMotor 2: A1B2C3D4-0002-1000-8000-00805F9B34FBMotor 3: A1B2C3D4-0003-1000-8000-00805F9B34FBMotor 4: A1B2C3D4-0004-1000-8000-00805F9B34FBMotor 5: A1B2C3D4-0005-1000-8000-00805F9B34FBDevice Name: A1B2C3D4-0006-1000-8000-00805F9B34FBOn the app side, constants live in a single shared file:
object BluetoothService { val SERVICE_UUID = Uuid.parse("A1B2C3D4-0000-1000-8000-00805F9B34FB") val DEVICE_NAME_CHAR_UUID = Uuid.parse("A1B2C3D4-0006-1000-8000-00805F9B34FB")}3. Characteristic property choices
All five motor characteristics carry PROPERTY_READ | PROPERTY_WRITE | PROPERTY_NOTIFY. This is broader than necessary.
READ was added for debugging: you can read the last written value back from nRF Connect without sending a command. In production, the peripheral state is owned by the app and READ is never called programmatically.
WRITE with response (PROPERTY_WRITE) means the BLE stack acknowledges every write at the protocol level before the next write proceeds. For motor commands where a dropped write leaves a motor stuck on or at the wrong speed, this is the right choice.
pmotor1 = pService->createCharacteristic( MOTOR_1_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);pmotor1->addDescriptor(new BLE2902());4. Descriptors: BLE2902 and what you are missing
BLE2902 is the Client Characteristic Configuration Descriptor. Every characteristic with PROPERTY_NOTIFY must have one attached. Without it, notify() sends to nobody and logs no error.
The profile also omits 0x2901 (Characteristic User Description), which holds a human-readable label. Adding it makes the profile readable in any generic BLE tool:
pmotor1->addDescriptor(new BLE2902());
BLEDescriptor *desc = new BLEDescriptor(BLEUUID((uint16_t)0x2901));desc->setValue("Motor 1 Control");pmotor1->addDescriptor(desc);This costs negligible memory and cuts debugging time significantly when inspecting the device cold.
5. The 2-byte command protocol
The payload written to each characteristic is the actual protocol. It is independent of GATT: the same encoding could run over any transport.
Byte 0: Command 0x01 Power on/off 0x02 Forward at speed 0x03 Reverse at speed 0x04 Timed run
Byte 1: Data For 0x01: 0x01 = on, 0x00 = off For 0x02/0x03: speed 0 to 127 For 0x04: duration in seconds, clamped to 60The firmware dispatches in four lines:
void processMotorCommand(MX1508 &motor, uint8_t cmd, int8_t value) { switch (cmd) { case 1: value == 1 ? motor.motorGo(128) : motor.motorStop(); break; case 2: motor.motorGo(value); break; case 3: motor.motorRev(value); break; default: Serial.printf("Unknown command: %d\n", cmd); }}Three known constraints in the current design: commands are not idempotent (the firmware re-executes on every write regardless of current state); there is no error response (notify fires unconditionally after every write whether the command was valid or not); the speed range is split across two commands (0x02 for forward, 0x03 for reverse) where a single signed byte would encode both direction and magnitude.
6. A revised profile for production
Collapsing five motor characteristics into one Motor Control characteristic with a three-byte payload makes adding a sixth motor a firmware-only change:
Service: [custom UUID]Motor Control (WRITE_WITH_RESPONSE): [motor_id, command, data] 3 bytesMotor Status (NOTIFY): [motor_id, status, speed] 3 bytes per motorDevice Config (READ | WRITE): UTF-8 device nameThe Motor Status characteristic closes the feedback loop that is currently open: the app can confirm commands landed and detect fault conditions without polling READ.
Testing and Verification
Connect with nRF Connect and expand the service:
- All characteristics appear under one service UUID.
- Motor characteristics show
WRITEandNOTIFYin the property list. - Expand any motor characteristic. The
BLE2902descriptor appears as “Client Characteristic Configuration”. - Write
01 01(hex) to Motor 1. The motor starts. - Write
01 00. The motor stops. - Subscribe to notifications on Motor 1 and write a command. A notification fires immediately after each write.
If 0x2901 descriptors are present, nRF Connect shows “Motor 1 Control” as the characteristic label instead of the raw UUID.
Pitfalls
Production Considerations
The current profile reuses SIG UUIDs, uses one characteristic per motor, and has no status feedback. None of these break correctness in a single-device, single-user context. In a multi-device or multi-developer context, all three become problems:
A custom base UUID is the highest-return change. Generate it once with uuidgen, define it in both the firmware and the app’s constants file, and every tool that touches the device will label it correctly.
The one-characteristic-per-motor design requires a profile change to add motors, which means a firmware update and an app update in lockstep. The three-byte [motor_id, command, data] encoding eliminates that coupling.
Going deeper
Do not build custom UUIDs on the SIG base
The suggested UUIDs in step 2 still end in -0000-1000-8000-00805F9B34FB. That suffix is the Bluetooth SIG base UUID, the block that every 16-bit and 32-bit SIG-assigned UUID expands into. Putting your own values in it means a future SIG assignment could collide with yours, and some tools will try to shorten your UUIDs into 16-bit form and mislabel them.
Generate one fully random 128-bit UUID and vary only the second group for each attribute. Nordic’s UART service uses this same pattern (6E400001-B5A3-…, 6E400002-B5A3-…).
$ uuidgen | tr 'A-Z' 'a-z'f3a10000-7c2e-4b8a-9d51-2c6f0e8a4b10// f3a1XXXX-7c2e-4b8a-9d51-2c6f0e8a4b10, XXXX identifies the attribute#define ATOM_UUID(id) "f3a1" id "-7c2e-4b8a-9d51-2c6f0e8a4b10"
#define SERVICE_UUID ATOM_UUID("0000")#define MOTOR_CONTROL_UUID ATOM_UUID("0001")#define MOTOR_STATUS_UUID ATOM_UUID("0002")#define DEVICE_CONFIG_UUID ATOM_UUID("0003")private fun atomUuid(id: String) = Uuid.parse("f3a1$id-7c2e-4b8a-9d51-2c6f0e8a4b10")
object BluetoothService { val SERVICE_UUID = atomUuid("0000") val MOTOR_CONTROL_UUID = atomUuid("0001") val MOTOR_STATUS_UUID = atomUuid("0002") val DEVICE_CONFIG_UUID = atomUuid("0003")}Reusing SIG UUIDs is the right call when the meaning really matches. The Device Information Service (0x180A) is a good example, covered next.
Version the protocol from day one
Firmware and app ship on different schedules. A phone with last month’s app will meet a device with this month’s firmware. If the app cannot tell which protocol the device speaks, the only safe behaviour is to assume the oldest one forever.
Expose the firmware version through the standard Device Information Service, which is exactly what it exists for:
BLEService *info = pServer->createService(BLEUUID((uint16_t)0x180A));BLECharacteristic *fw = info->createCharacteristic( BLEUUID((uint16_t)0x2A26), BLECharacteristic::PROPERTY_READ); // Firmware Revision Stringfw->setValue("1.2.0;proto=2");info->start();The app reads it once after connecting and picks an encoder. Keep the protocol number separate from the marketing version: firmware 1.2.0 and 1.2.1 can speak the same protocol 2.
Close the loop with sequenced status replies
The revised profile in step 6 adds a Motor Status notification, which tells the app what a motor is doing. It does not say which command caused it. If the app sends three commands quickly and one fails, it cannot tell which one. A one-byte sequence number fixes that:
Motor Control (WRITE): [seq, motor_id, command, data]Motor Status (NOTIFY): [seq, motor_id, result, speed]
result: 0x00 OK 0x01 Unknown command 0x02 Unknown motor_id 0x03 Value out of range 0x04 Driver faultvoid onControlWrite(BLECharacteristic *c) { std::string v = c->getValue(); if (v.size() != 4) return; uint8_t seq = v[0], id = v[1], cmd = v[2]; int8_t data = static_cast<int8_t>(v[3]); uint8_t result = validate(id, cmd, data); if (result == 0x00) result = applyCommand(id, cmd, data);
uint8_t reply[4] = { seq, id, result, currentSpeed(id) }; statusChar->setValue(reply, sizeof(reply)); statusChar->notify();}On the app, keep a small map of pending sequence numbers and complete each one when its reply arrives, with a timeout for replies that never come:
sealed interface CommandResult { data object Ok : CommandResult data class Rejected(val code: Int) : CommandResult data object TimedOut : CommandResult}
fun decodeStatus(bytes: ByteArray): Pair<Int, CommandResult> { require(bytes.size == 4) val seq = bytes[0].toInt() and 0xFF val result = bytes[2].toInt() and 0xFF return seq to if (result == 0) CommandResult.Ok else CommandResult.Rejected(result)}A one-byte counter wraps at 256, which is fine: it only needs to be unique among commands in flight at the same moment.
Prefer commands that set state
0x01 with data 0x01 means “power on”, which is already close to idempotent. Toggles are the commands to avoid: if “toggle motor” is written twice because the app retried after a lost acknowledgement, the motor ends up back where it started. Commands that state the target (“set motor 2 to reverse at 80”) give the same result no matter how many times they arrive, which makes retries safe. Have the firmware compare the requested state with the current one and skip the driver call when nothing changes.
Mind the MTU
The default ATT MTU is 23 bytes, which leaves 20 bytes of payload per write or notification. Four-byte commands fit easily. The device name does not always fit: a 24-character name written to Device Config will be truncated or fail, depending on the stack.
Raise the MTU on both sides. On the ESP32, set the preferred value before the first connection:
BLEDevice::setMTU(185);On Android, request it after connecting (Kable exposes requestMtu on Android peripherals). iOS negotiates the MTU automatically. Either way, design every message so it still works at 20 bytes, and treat a larger MTU as an optimisation.
Share test vectors between firmware and app
The protocol lives in two codebases in two languages. The cheapest way to keep them in agreement is a table of byte strings both sides must agree on:
| Meaning | Bytes (hex) |
|---|---|
| seq 7, motor 1, power on | 07 01 01 01 |
| seq 8, motor 2, forward at 100 | 08 02 02 64 |
| seq 9, motor 3, reverse at 127 | 09 03 03 7F |
| reply: seq 8 OK, speed 100 | 08 02 00 64 |
| reply: seq 9 out of range | 09 03 03 00 |
@Testfun forward_at_100_matches_firmware_vector() { assertContentEquals( "08020264".hexToByteArray(), encodeCommand(seq = 8, motorId = 2, command = Command.Forward, value = 100), )}Run the same vectors through the firmware’s validate and applyCommand with a native PlatformIO test (pio test -e native). When someone changes the encoding on one side only, a test fails instead of a motor misbehaving.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| nRF Connect labels characteristics as heart rate fields | SIG UUIDs reused for custom data | Move to a random 128-bit base |
| Tools show a 16-bit UUID you never defined | Custom UUID built on the SIG base | Use a base outside …-0000-1000-8000-00805F9B34FB |
| Long device names are cut off | Default 23-byte MTU | Raise the MTU, keep messages under 20 bytes by default |
| A retried command undoes itself | Toggle-style command | Send the target state instead |
| App cannot tell which command failed | Status has no correlation ID | Add a sequence byte to command and reply |
Wrapping Up
The AtomBrick profile works and the protocol is clean. Three specific decisions would not survive a production review: the reuse of SIG UUIDs, the per-motor characteristic structure, and the absence of status feedback in notifications. None are expensive to fix in a v2 profile: the firmware and app constants change, but the protocol bytes stay the same.
Start with the UUID change. Run uuidgen, replace 0x180D in the firmware and BluetoothService.SERVICE_UUID in the app, and redeploy. The rest of the protocol is unaffected.