Simvik

Fitness band: parse a heart-rate packet

Decode the standard Bluetooth Heart Rate Measurement, whose layout depends on its flags byte. A hard embedded C problem (Bluetooth Low Energy), run and…

hard · Bluetooth Low Energy · ble · gatt · parsing · product

Product: Fitness band (Wearables)

Requirement. The phone app and gym equipment read the band's heart rate through the standard Bluetooth Heart Rate Measurement characteristic (0x2A37). Its layout depends on the first byte, the flags:

  • bit 0: heart rate is one byte (0) or two bytes, low byte first (1);
  • bit 3: a 2-byte energy-expended field follows the heart rate (skip it);
  • bit 4: one or more RR intervals follow, 2 bytes each, low byte first, in units of 1/1024 s.

Parse the n bytes of d: set *bpm, convert up to 4 RR intervals to milliseconds (rounded to the nearest) into rr_ms, and set *rr_count. Return 0, or -1 if the packet is too short for its flags or the RR bytes are not a whole number of intervals.

Starter code

int hr_parse(const uint8_t *d, size_t n, uint16_t *bpm, uint16_t rr_ms[4], size_t *rr_count) {
  *bpm = d[1];
  *rr_count = 0;
  return 0;
}

Example tests

Resting, and a sprint finish

uint16_t bpm = 0, rr[4];
size_t k = 9;
uint8_t a[2] = { 0x00, 72 };
int r = hr_parse(a, 2, &bpm, rr, &k);
printf("%d %u %u\n", r, bpm, (unsigned)k);
uint8_t b[3] = { 0x01, 0x2C, 0x01 };
r = hr_parse(b, 3, &bpm, rr, &k);
printf("%d %u\n", r, bpm);

Expected output:

0 72 0
0 300

With beat-to-beat intervals

uint16_t bpm = 0, rr[4];
size_t k = 0;
uint8_t a[6] = { 0x10, 60, 0x00, 0x04, 0x00, 0x02 };
int r = hr_parse(a, 6, &bpm, rr, &k);
printf("%d %u %u %u %u\n", r, bpm, (unsigned)k, rr[0], rr[1]);

Expected output:

0 60 2 1000 500

Learn it first

More Bluetooth Low Energy problems