Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Analog and PWM

Smoothing and Filtering Noisy Readings

Tame noisy analog readings with averaging, a moving-average ring buffer, an exponential filter, a median filter for spikes and hysteresis, with runnable demos.

Analog readings jitter. A potentiometer that you are not touching might report 511, 512, 510, 513, 512. A light sensor flickers with the mains hum. A distance sensor throws an occasional wild value. If you feed raw readings straight into a decision or a motor, the output twitches. Filtering reduces the noise at the cost of some delay or detail. This lesson shows the four filters you will use most, how to pick one, and how to implement each in a few lines.

Each filter below runs in a stand-in on a recorded noisy signal so you can see the effect in numbers. The same functions drop straight into a sketch: replace the recorded array with analogRead().

Two kinds of noise

  • Random jitter around the true value, a few counts either way. Averaging fixes it.
  • Spikes (outliers): a single reading far from the rest, often from interference or a sensor glitch. Averaging smears a spike into its neighbors; a median filter removes it.

Averaging a burst

The simplest filter reads the pin several times and averages:

C++
int readAveraged(int pin, int samples) {
  long sum = 0;
  for (int i = 0; i < samples; i++) {
    sum += analogRead(pin);
  }
  return sum / samples;
}

Use long for the sum: 16 readings of 1023 overflow a 16-bit int. Averaging N independent samples reduces random noise by about the square root of N, so 16 samples give four times less noise. It costs N conversions of time (about 100 ยตs each).

Moving average (ring buffer)

Keep the last N readings, and report their average on every new reading. Instead of re-adding everything, subtract the oldest value and add the newest:

C++
const int N = 8;
int window[N];
int index = 0;
long total = 0;

int smooth(int reading) {
  total -= window[index];
  window[index] = reading;
  total += reading;
  index = (index + 1) % N;
  return total / N;
}
C Stand-in: moving average over a noisy signal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first few outputs are low because the buffer starts at zero; fill it with the first reading in setup() to avoid the warm-up dip. The trade-off: larger N means smoother output but a slower response to real changes (a lag of about N/2 samples).

Exponential moving average

An even cheaper filter needs one variable and no array. It blends the new reading with the previous output using a weight alpha between 0 and 1:

TEXT
filtered = alpha ร— reading + (1 โˆ’ alpha) ร— filtered

Small alpha (0.1) means heavy smoothing and slow response; alpha near 1 means almost no smoothing. With integers, use alpha as a shift: filtered += (reading - filtered) >> 3; for alpha = 1/8.

C Stand-in: exponential filter and its response to a step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output creeps toward 800 and never overshoots. Note the integer version stops slightly short, because small differences shift to zero. Keep the filtered value in a scaled form (multiply by 8 or 16) if you need full accuracy.

flowchart LR
    R["Raw reading"] --> F["Filter"]
    F --> D["Decision or output"]
    F -. "remembers" .-> M["Previous output or buffer"]
    M -.-> F

Figure: a filter combines the new reading with a remembered value before the result is used.

Median filter for spikes

Take the middle value of the last few readings. One wild reading is always at an end of the sorted list, so it is never chosen. A window of 3 or 5 is typical.

C Stand-in: median of 3 removes spikes, averaging smears them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The spikes 1023 and 0 disappear from the median column, while the average column swings by hundreds. A common combination is a median to kill spikes, followed by an exponential filter to smooth jitter.

Choosing and combining

Problem Filter Cost
Random jitter Moving average or exponential small lag
Occasional spikes Median of 3 to 5 small lag
Flicker at a threshold Hysteresis (analogRead lesson) none
Mains hum (50/60 Hz) Average over a multiple of 20 ms or 16.7 ms time
Hardware noise on the pin 100 nF capacitor, stable supply parts

Filter in software only after you have fixed what you can in hardware: short wires, a decoupling capacitor near the sensor, a clean power supply and a ground that is shared properly. Also scale the result afterwards with map() and constrain(), not before, to keep full resolution during filtering.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should the running sum in an averaging function be a long?

    int on an Uno holds up to 32767; the sum would overflow.
  2. 2. Which filter best removes single wild spikes?

    A median ignores outliers because they sit at the ends of the sorted window.
  3. 3. In an exponential filter, what does a smaller alpha do?

    Small alpha weights the old value heavily: heavy smoothing, slow response.
  4. 4. What is the downside of a larger moving-average window?

    The output follows true changes with a delay of about half the window.

Summary

  • Noise comes as random jitter (average it) and spikes (use a median).
  • A moving average uses a ring buffer; an exponential filter needs only one variable.
  • Larger windows and smaller alpha smooth more but react more slowly.
  • Use long for sums, fix hardware noise first, scale after filtering.
  • Combine a median filter and an exponential filter for robust sensor input.

Next: Temperature and Humidity Sensors (DHT and TMP36)