Moving Average Filter
Implement a moving average over the last N ADC samples (12-bit values in a uint16_t). ma_add(x) adds a sample and returns the current average. Until N samples have arrived, average over the samples received so far. Each call must be O(1).
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Keep a running sum. On each new sample subtract the value leaving the window and add the new one.
#include <stdio.h>
#include <stdint.h>
#define N 4u
uint16_t ma_add(uint16_t x)
{
static uint16_t win[N];
static uint32_t sum;
static uint32_t idx, count;
sum -= win[idx]; /* zero until the window fills */
sum += x;
win[idx] = x;
idx = (idx + 1u) % N;
if (count < N) count++;
return (uint16_t)(sum / count);
}
The running sum makes each update O(1) regardless of window size. A uint32_t sum cannot overflow for 12-bit samples unless N exceeds about one million. If N is a power of two, the division becomes a shift once the window is full.
Alternatives: an exponential moving average avg += (x - avg) >> k uses no buffer, which is popular on small MCUs; a median filter rejects spikes better than an average.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(ma_add(100) == 100);
CHECK(ma_add(200) == 150);
CHECK(ma_add(300) == 200);
CHECK(ma_add(400) == 250);
CHECK(ma_add(500) == 350); /* window is 200..500 */
CHECK(ma_add(4095) == 1323); /* (300+400+500+4095)/4 = 1323 */
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}