Simvik

ECG patch: smooth the heartbeat signal

A running four-sample average that keeps a constant cost per sample and starts cleanly. A medium embedded C problem (Digital filters: FIR and IIR), run and…

medium · Digital filters: FIR and IIR · moving-average · state · rounding · product

Product: Wearable ECG patch (Medical)

Requirement. The patch removes high-frequency muscle noise from the ECG before detecting beats, on a tiny MCU sampling hundreds of times a second, so each sample must cost the same few operations.

ecg_filter takes the next sample and returns the average of the last 4 samples (fewer at the start: the average of those received so far), rounded to the nearest integer, halves away from zero. Keep a running sum: subtract the sample that drops out instead of adding all four again.

Starter code

int16_t ecg_filter(ecg_t *f, int16_t x) {
  f->hist[f->idx] = x;
  f->sum += x;
  f->idx = (uint8_t)((f->idx + 1) % 4);
  return (int16_t)(f->sum / 4);
}

Example tests

A steady signal

ecg_t f;
memset(&f, 0, sizeof f);
for (int i = 0; i < 5; i++) printf("%d ", ecg_filter(&f, 100));
printf("\n");

Expected output:

100 100 100 100 100

A single spike spreads over four samples

ecg_t f;
memset(&f, 0, sizeof f);
int16_t x[9] = { 0, 0, 0, 0, 400, 0, 0, 0, 0 };
for (int i = 0; i < 9; i++) printf("%d ", ecg_filter(&f, x[i]));
printf("\n");

Expected output:

0 0 0 0 100 100 100 100 0

Learn it first

More Digital filters: FIR and IIR problems