Projects / Moving average versus median filter

Moving average versus median filter

Beginner1.3 hGuided buildReviewed

Build it step by step

0 of 7 done
  1. NANO681 lux

    Build the light divider

    LDR from 5V to A0, 10 k from A0 to GND.

  2. NANO

    Wire the knob and button

    Pot middle to A1, button from D2 to GND.

  3. NANO

    Upload the sketch

    Open the Serial Plotter at 115200 baud.

  4. NANO

    Watch the three lines

    Raw, Average and Median follow the room light.

  5. NANO

    Press the spike button

    Raw jumps, the average bumps and the median barely moves.

  6. NANO

    Turn the knob

    A bigger window makes both filters smoother and slower.

  7. NANO

    Wave your hand over the sensor

    See which filter follows real changes best.

In short

How do you build a moving average versus median filter?

A noisy light reading is cleaned by a moving average and by a median filter at the same time, and the serial plotter draws all three lines, so you can see why a median ignores a sudden spike while an average smears it. A button adds a fake spike on demand, and a knob sets how many readings each filter uses. You need Arduino Nano, LDR Photoresistor, Resistor 10 kΩ, Potentiometer 10 kΩ, Tactile push button 6 mm, Breadboard 830 Tie Points and Jumper wires male to male (40 pcs, 20 cm). It takes 7 steps and about 80 minutes.

Level
Beginner
Time
About 80 min
Parts
7

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
LDR leg 1Nano 5VTop of the light divider
LDR leg 2 and 10 k resistorNano A0Middle of the divider
10 k resistor other endNano GNDBottom of the divider
Pot outer legsNano 5V and GNDSets the window size
Pot middle legNano A1Window of 3 to 15 readings
Spike buttonNano D2 and GNDAdds one fake spike when pressed

Code

The light sensor and the 10 k resistor make a voltage divider, so the reading on A0 rises and falls with the light. Every 20 milliseconds the sketch stores the newest reading in a small ring of 15 numbers, then works out two cleaned-up values from the newest few readings. The average adds them up and divides, so one wild reading drags the whole answer up and then drags it down again as it leaves the window. The median sorts the readings and takes the middle one, so a single wild reading is simply ignored. Press the spike button and the raw line jumps by about 400 for one reading: the average shows a small bump that lingers, and the median stays almost flat. The knob sets how many readings each filter uses, from 3 to 15, and a bigger window is smoother but slower to follow a real change. Open the Serial Plotter and set it to 115200 baud to see the three lines in different colours. Try waving your hand slowly over the sensor to see which filter follows a real change better. The median needs the readings sorted each time, which is fine for 15 numbers but would be slow for hundreds.

Runs on a virtual Arduino Nano in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

// No extra libraries. Open Tools > Serial Plotter at 115200 baud.
const uint8_t LDR_PIN = A0;
const uint8_t POT_PIN = A1;
const uint8_t BTN_PIN = 2;
const uint8_t N_MAX = 15;                 // biggest window

int buf[N_MAX];
uint8_t head = 0;                         // next slot to write
uint8_t filled = 0;                       // how many slots hold readings
bool prevBtn = false;
bool spikeNext = false;
unsigned long lastSample = 0;

int medianOf(const int *src, uint8_t n) {
  int tmp[N_MAX];
  for (uint8_t i = 0; i < n; i++) tmp[i] = src[i];
  for (uint8_t i = 1; i < n; i++) {       // small insertion sort
    int key = tmp[i];
    int j = i - 1;
    while (j >= 0 && tmp[j] > key) { tmp[j + 1] = tmp[j]; j--; }
    tmp[j + 1] = key;
  }
  return tmp[n / 2];
}

void setup() {
  pinMode(BTN_PIN, INPUT_PULLUP);
  Serial.begin(115200);
}

void loop() {
  bool b = (digitalRead(BTN_PIN) == LOW);
  if (b && !prevBtn) spikeNext = true;
  prevBtn = b;

  unsigned long now = millis();
  if (now - lastSample < 20) return;      // 50 readings a second
  lastSample = now;

  int raw = analogRead(LDR_PIN);
  if (spikeNext) {                        // a fake glitch, like a torch flick
    raw = min(1023, raw + 400);
    spikeNext = false;
  }

  buf[head] = raw;
  head = (head + 1) % N_MAX;
  if (filled < N_MAX) filled++;

  uint8_t n = map(analogRead(POT_PIN), 0, 1023, 3, N_MAX);
  n |= 1;                                 // keep the window odd
  if (n > N_MAX) n = N_MAX;
  if (n > filled) n = filled;

  int win[N_MAX];
  long sum = 0;
  for (uint8_t k = 0; k < n; k++) {       // the n newest readings
    int v = buf[(head + N_MAX - 1 - k) % N_MAX];
    win[k] = v;
    sum += v;
  }
  int avg = sum / n;
  int med = medianOf(win, n);

  Serial.print(F("Raw:"));
  Serial.print(raw);
  Serial.print(F(",Average:"));
  Serial.print(avg);
  Serial.print(F(",Median:"));
  Serial.println(med);
}

What the serial monitor should show

Open the serial monitor at the baud rate in the code. This is what our simulator prints for a virtual Arduino Nano with its sensors at their default values. Your numbers will follow your real readings, but the format should match.

Raw:512,Average:512,Median:512
Raw:513,Average:512,Median:512
Raw:512,Average:512,Median:512
Raw:511,Average:512,Median:512
Raw:512,Average:512,Median:512
Raw:511,Average:511,Median:512

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
Steady lightThe three lines sit close together
Spike buttonRaw jumps, average bumps, median stays flat
Knob to the leftA window of 3, lines follow quickly
Knob to the rightA window of 15, smoother but slower
Slow hand waveAverage and median both follow it

If it does not work

Plotter shows one line

Check the baud rate is 115200 and the text has commas.

Reading stuck near 0 or 1023

Check the divider and that the 10 k is to GND.

Spike does nothing

Check the button goes to D2 and GND.

Lines look the same

Turn the knob up and press the spike button.

Plotter is empty

Close and reopen the Serial Plotter after the upload.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the moving average versus median filter?

Arduino Nano, LDR Photoresistor, Resistor 10 kΩ, Potentiometer 10 kΩ, Tactile push button 6 mm, Breadboard 830 Tie Points and Jumper wires male to male (40 pcs, 20 cm).

How long does the moving average versus median filter take to build?

About 80 minutes for a beginner maker, in 7 steps.

How do I know the moving average versus median filter works?

Steady light: The three lines sit close together. Spike button: Raw jumps, average bumps, median stays flat. Knob to the left: A window of 3, lines follow quickly.

Plotter shows one line: what should I check?

Check the baud rate is 115200 and the text has commas.

Reading stuck near 0 or 1023: what should I check?

Check the divider and that the 10 k is to GND.

Spike does nothing: what should I check?

Check the button goes to D2 and GND.

Lines look the same: what should I check?

Turn the knob up and press the spike button.