Moving average, median and Kalman filters can all make sensor data look smoother, but they solve different noise problems. Choosing the wrong one can hide real events, add delay, or create confidence in numbers that are still biased.
Before filtering anything, first ask what kind of error you have: random high-frequency noise, isolated spikes, quantization, drift, vibration, or uncertainty in a dynamic physical model.
Moving average: simplest for random high-frequency noise
A simple moving average replaces each output with the average of the most recent N samples:
y[k] = (x[k] + x[k-1] + ... + x[k-N+1]) / N
It is easy to implement, predictable and cheap enough for most microcontrollers.
Where it works well
- ADC readings with small zero-mean fluctuations.
- Slow physical variables such as temperature.
- Displays where visual stability matters more than immediate response.
- Applications where a fixed amount of smoothing is acceptable.
The cost: delay
A larger window smooths more aggressively but delays changes. For a causal moving average of N samples, the filtered response is effectively centered behind the newest sample. If a control loop needs fast reaction, excessive averaging can make the controller respond late.
Efficient moving average on a microcontroller
Do not sum the entire buffer every time if CPU time matters. Maintain a running sum:
#define N 16
static uint16_t buffer[N];
static uint32_t sum;
static size_t index;
uint16_t moving_average(uint16_t sample)
{
sum -= buffer[index];
buffer[index] = sample;
sum += sample;
index = (index + 1u) % N;
return (uint16_t)(sum / N);
}
Choose the accumulator width so the maximum possible sum cannot overflow.
Median filter: best for isolated spikes
A median filter sorts the samples inside a local window and outputs the middle value rather than the average. SciPy’s reference implementation describes exactly this behavior and requires an odd kernel size for its standard median-filter operation.
Example window:
[101, 102, 2500, 100, 103]
The mean is badly distorted by the 2500 spike. The median remains close to the normal signal.
Median filters are strong when:
- Noise contains isolated large outliers.
- A sensor occasionally produces impossible spikes.
- You want to preserve sharp transitions better than a large mean filter would.
Median filters are not free
The window values must be ordered enough to find the middle value. On a small MCU, a tiny fixed window such as 3 or 5 samples is often practical; a large median window can cost significantly more CPU than a running average.
Do not use a median filter to hide a broken interface
If spikes are caused by an I2C bus error, loose wire, ADC overrange or packet corruption, the correct fix is to repair the acquisition path. A median filter can mask the symptom and make diagnostics harder.
Kalman filter: model-based state estimation
A Kalman filter is not simply a “better smoothing filter.” It combines a system model with noisy measurements to estimate an internal state and its uncertainty.
R. E. Kalman’s 1960 paper formulated the recursive linear filtering and prediction approach around a state-transition model and an evolving error covariance.
A simple example
Suppose a moving object has position and velocity. A Kalman filter can use the motion model to predict the next state, then correct that prediction when a noisy position measurement arrives.
The filter needs models for:
- How the state evolves.
- How measurements relate to the state.
- Process uncertainty.
- Measurement uncertainty.
Why Kalman filters are often misused
If you choose noise covariance values only until the graph “looks nice,” the filter may be cosmetically smooth without representing real uncertainty.
Kalman filtering is strongest when the state model carries useful information that a simple smoothing window does not have—for example, combining accelerometer and position measurements or estimating velocity that is not measured directly.
Moving average vs median vs Kalman
| Problem | Best starting point | Main trade-off |
|---|---|---|
| Small random fluctuations | Moving average | Delay increases with window size |
| Occasional large spikes | Median | More computation and window delay |
| Dynamic state with known model | Kalman | Model/tuning complexity |
| Slow temperature display | Moving average | Slower visible response |
| Ultrasonic sensor with sporadic outliers | Median | Can hide repeated real transitions if window is too large |
| Position + velocity estimation | Kalman | Requires a credible state model |
Sampling rate comes before filter choice
A digital filter cannot repair aliasing that already happened during sampling. If the sensor contains frequency content above what your sample rate can represent, those components can fold into false lower frequencies.
Read our sampling-rate guide before tuning a filter around suspicious data.
Filtering does not remove sensor bias
A stable sensor that is always 3 °C too high will remain wrong after averaging. Filtering reduces certain forms of noise; calibration corrects systematic relationship errors.
Separate:
- Noise: variation around the measurement.
- Bias: consistent offset.
- Scale error: slope/gain mismatch.
- Drift: error that changes with time or temperature.
How to choose the window size
For moving average and median filters, convert window length into real time:
window_time = N / sample_rate
A 20-sample window means very different behavior at 10 samples/s and 10 kHz.
Choose the window from the fastest real signal change you must preserve—not from how smooth you want the graph to look.
Test with step response
One of the fastest ways to compare filters is to feed them data containing:
- A steady baseline.
- Random noise.
- A single large spike.
- A sudden real step change.
- A slow ramp.
Then compare how quickly each filter follows the real step and how strongly it rejects the artificial spike.
Do not filter inside a control loop without checking phase delay
Filtering a feedback measurement changes the dynamics of the control loop. A large smoothing window can add enough delay to reduce stability margin.
For a display value, heavy smoothing may be harmless. For current control, motor position or fast pressure regulation, the same filter can be dangerous.
A practical embedded workflow
- Log raw sensor data first.
- Measure sample interval and timing jitter.
- Identify whether errors are random noise, outliers, bias or drift.
- Try the simplest filter that matches the error.
- Evaluate real-time delay, not only visual smoothness.
- Test the filter against real step changes.
- Measure CPU and RAM cost on the target MCU.
- Keep raw data available during development so filtering does not hide faults.
Primary references
- SciPy: median filter reference
- SciPy Signal Processing tutorial
- R. E. Kalman, “A New Approach to Linear Filtering and Prediction Problems,” 1960
Bottom line
Use a moving average for simple random noise, a median filter for isolated outliers, and a Kalman filter when a real system model can improve state estimation. The best filter is the simplest one that removes the unwanted error without destroying the signal information your application actually needs.