pot · A0MCUATmega328PADC · SRAMbuf[0]buf[1]buf[2]buf[3]totalavgema1void addReading() {2 int x = analogRead(A0);3 total += x - buf[i];4 buf[i] = x;5 i = (i + 1) % N;6 avg = total / N;7 ema += (x - ema) / 4;8}i
048121620460500540580620reading number (one per 100 ms)ADC valueREADING ON A0raw readingaverage of 4emamedian of 3
Back: the board, a knob on A0 and the microcontroller with its variables in SRAMFront: addReading(), the firmware that runs once per reading; below: the readings plottedTokens: readings, the value pushed out of the buffer, and the new averageA potentiometer on A0 of an Arduino Uno R3, read every 100 ms. Held still, it reads 502, 497, 503, 498: noise. addReading() keeps the last 4 readings in a ring buffer with a running total, so each new reading costs two sums: the average stays between 499 and 501. An exponential average needs one variable. Both lag behind a real change, and both are fooled by a single spike that a median of three ignores.

Noise

  1. The knob on A0 is held still, yet analogRead returns 502, 497, 503, 498. That jitter is noise: interference picked up by the wires and the supply, plus the converter's own error of up to ±2 steps.

Moving average

Other smoothers, and the cost

What happens

;; step 1/8 · noise
board     Arduino Uno R3 (ATmega328P), knob on A0
ADC       10 bits: 0..1023, about 100 µs per analogRead
readings  502  497  503  498   (knob not moving)
noise     wires and supply pick up interference;
          the ADC itself is accurate to ±2 LSB (steps)

The readings are an illustrative example, not a recording: a held knob on a breadboard really does wander by a few steps, but the exact numbers here were chosen for the story. Every average, ema and median is computed from them exactly as the sketch does it. setup() calls addReading() 4 times before loop() starts, so the buffer is full before the average is used. Slots start at 0, so during those first calls avg is too low; the Arduino "Smoothing" example has the same start-up effect. setup() then sets ema = avg so the exponential average does not start from 0.