Simvik

Moving average filter

Maintain the average of the last four samples in constant time. A medium embedded C problem (Fixed-point and signal processing), run and graded in the browser.

medium · Fixed-point and signal processing · filters · circular-buffer

A moving average smooths a noisy signal. Recomputing the sum over the whole window for every sample is wasteful: keep a running sum instead, subtracting the sample that leaves and adding the one that arrives. A zero-initialised avg_t is empty.

Add sample to the filter and return the average of the samples in the window, dividing by the number received so far while the window is still filling. The division truncates toward zero.

Starter code

int16_t avg_update(avg_t *f, int16_t sample) {
  // Replace the oldest sample, keep `sum` up to date, return sum / count.
  return sample;
}

Example tests

While the window fills

avg_t f = { 0 };
for (int16_t s = 10; s <= 40; s += 10) printf("%d ", avg_update(&f, s));
printf("\n");

Expected output:

10 15 20 25

Once the window is full

avg_t f = { 0 };
int16_t out = 0;
for (int16_t s = 10; s <= 50; s += 10) out = avg_update(&f, s);
printf("%d\n", out);

Expected output:

35

Learn it first

More Fixed-point and signal processing problems