flowchart TB S["Service<br/>1c6865f9-…"] --> RX["RX characteristic (Write)<br/>9e32b171-…<br/>phone → device: commands"] S --> TX["TX characteristic (Notify)<br/>02b89422-…<br/>device → phone: responses & measurement data"]
7 Event source ③: BLE
7.1 Basic BLE terms
| Term | Meaning |
|---|---|
| Peripheral | The side that waits for connections. This device |
| Central | The side that initiates the connection. A smartphone or PC |
| Advertising | Packets the peripheral sends periodically saying “I’m here”. They carry the name and service UUIDs |
| GATT | The framework for exchanging data after connecting. A service contains characteristics (containers for values) |
| Write | Central → peripheral: write a value |
| Notify | Peripheral → central: send a value (only if the central has enabled the subscription) |
| UUID | Identifier of a service or characteristic. Custom ones use random 128-bit values |
7.2 GATT layout of this sample
It is a simple layout with two characteristics in one service: RX, which receives commands, and TX, which returns responses (the same idea as the Nordic UART Service).
7.3 Implementation
#ifndef DRV_BLE_H
#define DRV_BLE_H
#include <Arduino.h>
// Service and characteristic UUIDs (generated for this hands-on)
#define BLE_SERVICE_UUID "1c6865f9-d683-423a-ab14-7bfcbe71ca56"
#define BLE_RX_CHARA_UUID "9e32b171-c5a8-429e-af49-79eebdb398c2" // phone → device (Write)
#define BLE_TX_CHARA_UUID "02b89422-f15b-4388-a22e-ddaa5a100258" // device → phone (Notify)
#define BLE_DEVICE_NAME "HANDSON_NRF52"
void ble_init();
bool ble_is_connected();
// Send on the TX characteristic (only when connected and Notify is enabled)
bool ble_send(const uint8_t *data, uint16_t len);
#endif // DRV_BLE_H#include "drv_ble.h"
#include "app_event.h"
#include <bluefruit.h>
static BLEService s_service(BLE_SERVICE_UUID);
static BLECharacteristic s_rx(BLE_RX_CHARA_UUID);
static BLECharacteristic s_tx(BLE_TX_CHARA_UUID);
static volatile bool s_connected = false;
// --- Callbacks (called inside the BLE task; here too we only post events) -----
static void on_connect(uint16_t conn_handle)
{
s_connected = true;
event_post(EVT_BLE_CONNECTED);
}
static void on_disconnect(uint16_t conn_handle, uint8_t reason)
{
s_connected = false;
event_post(EVT_BLE_DISCONNECTED, &reason, 1);
}
// Command format: [group, command, args...]
// 0x00 0x01 : get device info
// 0x01 0x00 : start measurement
// 0x01 0x01 : stop measurement
// 0x02 0x01 : get latest value
static void on_rx_write(uint16_t conn_hdl, BLECharacteristic *chr, uint8_t *data, uint16_t len)
{
if (len < 2)
return;
uint16_t cmd = ((uint16_t)data[0] << 8) | data[1];
const uint8_t *args = data + 2;
uint8_t args_len = (uint8_t)(len - 2);
switch (cmd)
{
case 0x0001: event_post(EVT_BLE_CMD_GET_INFO, args, args_len); break;
case 0x0100: event_post(EVT_BLE_CMD_MEAS_START, args, args_len); break;
case 0x0101: event_post(EVT_BLE_CMD_MEAS_STOP, args, args_len); break;
case 0x0201: event_post(EVT_BLE_CMD_GET_LATEST, args, args_len); break;
default: break; // discard unknown commands
}
}
void ble_init()
{
Bluefruit.begin();
Bluefruit.autoConnLed(false); // the LED is controlled by the app (ui_update)
Bluefruit.setTxPower(0);
Bluefruit.setName(BLE_DEVICE_NAME);
Bluefruit.Periph.setConnectCallback(on_connect);
Bluefruit.Periph.setDisconnectCallback(on_disconnect);
s_service.begin();
s_tx.setProperties(CHR_PROPS_NOTIFY);
s_tx.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
s_tx.setMaxLen(20);
s_tx.begin();
s_rx.setProperties(CHR_PROPS_WRITE | CHR_PROPS_WRITE_WO_RESP);
s_rx.setPermission(SECMODE_OPEN, SECMODE_OPEN);
s_rx.setMaxLen(20);
s_rx.setWriteCallback(on_rx_write);
s_rx.begin();
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
Bluefruit.Advertising.addService(s_service);
Bluefruit.ScanResponse.addName();
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(160, 800); // units of 0.625 ms: 100 ms (fast) to 500 ms (slow)
Bluefruit.Advertising.setFastTimeout(30); // fast advertising for the first 30 seconds
Bluefruit.Advertising.start(0); // 0 = keep going without stopping
}
bool ble_is_connected()
{
return s_connected;
}
bool ble_send(const uint8_t *data, uint16_t len)
{
if (!s_connected || !s_tx.notifyEnabled())
return false;
return s_tx.notify(data, len);
}7.3.1 Callbacks only convert to events
The Bluefruit library’s callbacks (connect, disconnect, write) are called inside the task that processes BLE events. Heavy processing here stalls all BLE communication, so they only do
- connect / disconnect →
EVT_BLE_CONNECTED/EVT_BLE_DISCONNECTED - write → interpret the command, convert it to the corresponding event ID, and post the arguments as payload
What a command means (what to do) is decided by the handlers of the state transition table. Even for the same “start measurement” command, the behaviour — start measuring if idle, ignore it if already measuring — is determined by the table alone, without touching the BLE code.
7.3.2 The connection-state flag
s_connected is updated before posting the event inside the callback. The LED display (ui_update()) and the decision whether sending is possible (ble_send()) only want to know “am I connected right now?”, so they read the flag directly. On the other hand, processing of the form “do something when connected” is written in the handler for the event (EVT_BLE_CONNECTED).
7.4 Command and response protocol
With your own BLE device, you have to decide the byte-sequence format (protocol) yourself. In this sample, the first 2 bytes indicate the kind.
7.4.1 Commands (phone → device, Write to RX)
| Bytes | Meaning | Corresponding event |
|---|---|---|
00 01 |
Get device info | EVT_BLE_CMD_GET_INFO |
01 00 |
Start measurement | EVT_BLE_CMD_MEAS_START |
01 01 |
Stop measurement | EVT_BLE_CMD_MEAS_STOP |
02 01 |
Get latest value | EVT_BLE_CMD_GET_LATEST |
7.4.2 Responses / notifications (device → phone, Notify on TX)
| Bytes | Meaning |
|---|---|
80 01 MJ MN PT |
Device info (firmware version) |
80 02 LL HH |
Latest acceleration magnitude [mg] (little-endian 16 bit) |
81 00 SL SH N ML MH XL XH |
Aggregate sent every second during measurement: sequence number (16 bit), sample count, mean [mg], max [mg] |
#include "app_meas.h"
#include "drv_ble.h"
volatile uint16_t g_latest_acc_mg = 0;
MeasSummary g_last_summary = {};
static uint16_t s_seq = 0;
static uint8_t s_n = 0;
static uint32_t s_sum = 0;
static uint16_t s_max = 0;
void meas_begin()
{
s_seq = 0;
s_n = 0;
s_sum = 0;
s_max = 0;
g_last_summary = {};
}
void meas_add_sample(uint16_t acc_mg)
{
s_n++;
s_sum += acc_mg;
if (acc_mg > s_max)
s_max = acc_mg;
}
MeasSummary meas_close_second()
{
MeasSummary s;
s.seq = s_seq++;
s.n = s_n;
s.mean_mg = (s_n > 0) ? (uint16_t)(s_sum / s_n) : 0;
s.max_mg = s_max;
s_n = 0;
s_sum = 0;
s_max = 0;
g_last_summary = s;
return s;
}
// --- BLE responses ----------------------------------------------------
// The first 2 bytes of a response are the "kind": 0x80 = response, 0x81 = notification (measurement data)
void reply_info()
{
uint8_t buf[5] = {0x80, 0x01, FW_VERSION_MAJOR, FW_VERSION_MINOR, FW_VERSION_PATCH};
ble_send(buf, sizeof(buf));
}
void reply_latest()
{
uint16_t v = g_latest_acc_mg;
uint8_t buf[4] = {0x80, 0x02, (uint8_t)(v & 0xff), (uint8_t)(v >> 8)};
ble_send(buf, sizeof(buf));
}
void notify_summary(const MeasSummary &s)
{
uint8_t buf[9] = {
0x81, 0x00,
(uint8_t)(s.seq & 0xff), (uint8_t)(s.seq >> 8),
s.n,
(uint8_t)(s.mean_mg & 0xff), (uint8_t)(s.mean_mg >> 8),
(uint8_t)(s.max_mg & 0xff), (uint8_t)(s.max_mg >> 8),
};
ble_send(buf, sizeof(buf));
}- Put a byte indicating the kind at the beginning so the receiver can branch easily
- For multi-byte numbers, decide and document the endianness (byte order) (both the nRF52840 and JavaScript’s
DataViewhandle little-endian easily) - One Notify holds 20 bytes by default (ATT MTU 23 − 3-byte header). For data larger than that, negotiate a larger MTU or split it
- Provide a version query command from the start, for future extension
7.5 Advertising settings
| Setting | Value | Meaning |
|---|---|---|
setInterval(160, 800) |
100 ms / 500 ms | Advertising interval in fast and slow modes (units of 0.625 ms) |
setFastTimeout(30) |
30 s | Advertise fast only for the first 30 seconds after boot/disconnect, then slow down to save power |
restartOnDisconnect(true) |
Automatically restart advertising after a disconnect |
The shorter the advertising interval, the easier the device is to find and the faster it connects, at the cost of higher power consumption.
7.6 Checking it works
You can check with the smartphone app nRF Connect for Mobile (by Nordic, iOS / Android).
- Scan and connect to
HANDSON_NRF52 - Enable Notify on the TX characteristic (
02b89422-…) - Write
0001to the RX characteristic (9e32b171-…) →80 01 01 00 00(version 1.0.0) arrives on TX - Writing
0100starts measurement: the LED blinks red, and81 00 …arrives every second
From Chrome / Edge on a PC, you can operate it directly from this page using the BLE console in Chapter 9.