Moving average with a running sum
Average the last few samples with one add and one subtract per sample. An easy embedded C problem (Digital filters: FIR and IIR), run and graded in the browser.
easy · Digital filters: FIR and IIR · dsp · filter · ring-buffer
Write ma_update(f, x): add sample x and return the average of the last MA_LEN samples, or of all samples so far if there have been fewer. Divide with C's /, which rounds toward zero.
Do not add up the buffer on every call: keep sum up to date by adding the new sample and subtracting the one it replaces. The samples are full 16-bit values, so the sum needs more than 16 bits.
Starter code
int16_t ma_update(ma_t *f, int16_t x) {
f->buf[f->pos] = x;
f->pos = (f->pos + 1) % MA_LEN;
int16_t sum = 0;
for (int i = 0; i < MA_LEN; i++) sum += f->buf[i];
return sum / MA_LEN;
}Example tests
A ramp
int16_t x[] = { 10, 20, 30, 40, 50, 60 };
feed(x, 6);Expected output:
10 15 20 25 35 45Learn it first
- Digital filters: FIR and IIR · Moving averages, FIR and IIR filters, biquads and notch filters.
More Digital filters: FIR and IIR problems
- Exponential smoothing without stalling · A first-order IIR filter in integers that keeps extra fractional bits so it reaches the input.
- Fix: the filter output is one sample late · An FIR filter's impulse response comes out shifted by one sample.
- ECG patch: smooth the heartbeat signal · A running four-sample average that keeps a constant cost per sample and starts cleanly.