A digital filter is an algorithm that modifies a sequence of samples to reduce noise or highlight useful information.
You have just connected your LM35 temperature sensor or your ultrasonic distance sensor.
You look at the Serial Monitor and see this:
20.1, 20.2, 20.1, 25.8, 19.9, 20.1...
Wait, 25.8? Did the temperature rise 5 degrees in one millisecond? No. It’s noise.
In the real world, electrical signals are dirty. Motors starting up, long wires acting as antennas, and the microcontroller’s ADC instability all mess up your data. If you use that “raw” value to make decisions (e.g., turn on a fan), your system will go crazy turning on and off.
Today we’ll look at the 4 standard software techniques to turn a noisy signal into a smooth, elegant line.
Technique Comparison
| Technique | Ideal for… | Computational Cost |
|---|---|---|
| Sample Averaging | Random noise | High if it blocks during many readings |
| Moving Average | General smoothing | High (RAM usage) |
| Median Filter | Removing wild spikes | Medium (requires sorting) |
| EMA | General use (Standard) | Very Low (Fast and lightweight) |
Averaging Several Samples
This is a basic technique that works well against uncorrelated random noise. Instead of reading the sensor once and trusting it, we read it 10, 50, or 100 times in quick succession and take the average.
Why does it work? White noise is random (sometimes it adds, sometimes it subtracts). By summing many samples, the noise tends to cancel itself out, while the real signal remains.
// Example: Simple averaging
float smoothSensorRead() {
long sum = 0;
int n_samples = 50;
for(int i=0; i<n_samples; i++) {
sum += analogRead(A0);
delay(1); // Small pause for stability
}
return (float)sum / n_samples;
}- Advantage: Very easy to program.
- Disadvantage: “Blocks” the processor. If you take 100 samples with pauses, your code freezes during that time.
The Simple Moving Average (SMA)
Imagine a window sliding over your data. You take the last 10 readings, average them, and that’s your output. When a new data point comes in, you drop the oldest one.
This smoothes the curve wonderfully.
- The memory problem: To do this on an Arduino, you need an array (list) to store the last N values.
- If you want to average 50 values, you need to spend RAM to store 50 integers. On small chips, this is a luxury.
The Median Filter
Sometimes the noise isn’t smooth; it’s spikes.
Imagine a distance sensor:
10cm, 10cm, 11cm, 800cm, 10cm...
That “800” is a read error.
- If you take the average: (10+10+11+800+10) / 5 = 168 cm. The average is ruined by the spike!
- If you take the median: Sort the values (
10, 10, 10, 11, 800) and take the middle one -> 10 cm.
The median is robust against isolated, far-off values. It’s useful for ultrasonic or infrared sensors that produce occasional spikes.
The EMA Filter (Exponential Moving Average)
The EMA filter (or digital low-pass filter) smooths readings without storing a full window of samples: it only needs to keep the previous state.
It works by giving a “weight” to the new reading against the accumulated history.
The formula:
Where alpha is a number between 0 and 1 that defines the smoothness:
- Alpha = 1.0: No filter (takes the current value as is).
- Alpha = 0.1: The new value only affects 10%. 90% of the value depends on past history. (Very smooth, but slow).
Code implementation:
float filteredValue = 0; // Filter state
bool initialized = false;
float alpha = 0.05; // Smoothing factor (0.01 to 1.0)
void loop() {
int rawReading = analogRead(A0);
if (!initialized) {
filteredValue = rawReading;
initialized = true;
} else {
filteredValue = (alpha * rawReading) + ((1.0 - alpha) * filteredValue);
}
Serial.println(filteredValue);
delay(10);
}What are its advantages?
- Memory: You only need 1 variable (
filteredValue). - Adjustment: Changing
alphaadjusts how much it filters. - Approximate equivalence: with a constant sampling period and a well-chosen
alpha, it behaves like a first-order low-pass filter comparable to an RC filter.
The Price to Pay: Lag
The more you filter a signal (more averages, or a smaller alpha in EMA), the more stable the number will be, but the slower it will react.
- If you’re measuring room temperature, a 2-second delay doesn’t matter. Filter heavily!
- If you’re measuring a drone’s gyroscope to avoid a crash, you need an instant reaction. Filter lightly!
The art of engineering lies in finding the balance between a clean signal and a fast response.