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 25Once 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:
35Learn it first
- Fixed-point and signal processing · Scaling, rounding, saturation and filters without floating point.
More Fixed-point and signal processing problems
- Saturating addition · Add two 16-bit samples and clamp instead of wrapping.
- Q15 multiplication · Multiply two fractional fixed-point numbers.
- ADC counts to millivolts · Convert a 12-bit ADC reading to a voltage with correct rounding.
- Thermostat with hysteresis · Decide a heater state with two thresholds so it does not chatter.
- Exponential moving average · Implement a one-pole low-pass filter with a shift instead of a multiply.
- Linear interpolation · Interpolate between two calibration points without overflow.
- Temperature conversion with rounding · Convert tenths of a degree Celsius to Fahrenheit and round correctly below zero.
- Integer square root · Compute the square root of a 32-bit value without floating point.
- PI controller with anti-windup · Implement an integer PI control step with clamped integral and output.
- Fix: the battery always shows 0 % · Dividing before multiplying throws the whole result away in integer arithmetic.
- Fix: long measurements come out tiny · A tick count is scaled to microseconds through a product that overflows 32 bits.
- Hearing aid: amplify without wrapping · Apply a fixed-point gain to an audio sample, rounding and saturating instead of wrapping round.