Smoothing noisy readings
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Hold a knob still and analogRead still returns a different number each time: 502, 497, 503, 498. That jitter is noise, and firmware tames it by averaging. Follow an Arduino Uno R3 as it keeps the last 4 readings in a ring buffer with a running total, so each new reading costs just two sums. Then meet the exponential moving average, which needs one variable, see why every smoother lags behind a real change, and watch a median of three throw away a spike that fools both averages. The Signals lessons on moving averages and IIR filters explain the maths behind these filters; here we write them in firmware.
Same knob, different numbers
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.
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)اقرأ الدرس خطوة بخطوة
Same knob, different numbers
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.
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)Keep the last four readings
Each reading goes into an array, buf, at slot i. Then i moves on: 0, 1, 2, 3 and back to 0, so the newest reading always overwrites the oldest. This is called a ring buffer.
line 4 buf[i] = x; store the reading in slot i line 5 i = (i + 1) % N; % is the remainder: 3 + 1 -> 0 buf [502, 497, 503, 498] i 0 -> 1 -> 2 -> 3 -> 0 ring buffer: a fixed array whose write slot wraps aroundAdd them up, divide by four
Line 3 kept a running total: 502 + 497 + 503 + 498 = 2000. Line 6 divides by N: avg = 500. Noise pushes some readings up and some down, so in a sum they partly cancel.
line 3 total += x - buf[i]; (the empty slots held 0) total 502 + 497 + 503 + 498 = 2000 line 6 avg = total / N; avg 2000 / 4 = 500A new reading pushes one out
Reading 506 arrives. Line 3 takes the oldest, 502, out of the total and adds 506: 2000 − 502 + 506 = 2004. Line 4 overwrites slot 0, and the average becomes 501. Two sums per reading, however big N is.
line 2 x = 506 line 3 total = 2000 - buf[0] + x = 2000 - 502 + 506 = 2004 line 4 buf[0] = 506 buf = [506, 497, 503, 498] line 5 i = 1 line 6 avg = 2004 / 4 = 501 (whole numbers: 501 -> 501)A calmer line
More readings stream in. The raw numbers wander from 496 to 503; the average stays between 499 and 501. Averaging N readings cuts random noise by about √N: four readings halve it, sixteen cut it to a quarter.
readings 499 501 496 503 avg 501 501 500 499 noise random noise shrinks by about √N: N = 4 -> 1/2, N = 16 -> 1/4, N = 100 -> 1/10One number instead of four
Line 7 keeps an exponential moving average, ema. Each reading moves it a quarter of the way toward itself: reading 498 takes ema from 500.4 to 499.8. It needs no array, just one variable.
line 7 ema += (x - ema) / 4; reading 498: 500.4 + (498 - 500.4) / 4 = 499.8 same as ema = 0.25 * x + 0.75 * ema (a single pole low-pass filter) memory one float, whatever the smoothingThe price: lag
Now the knob turns and readings jump to about 540. avg climbs 510, 519, 531, 540: four readings, 0.4 s, to catch up. ema is slower still: 511, 517, 524, 528. Smoother always means slower.
readings 541 538 543 539 knob turned avg 510 519 531 540 caught up after N = 4 readings ema 511 517 524 528 about 2/3 of the way after 4 time one reading per 100 ms: 4 readings = 0.4 s bigger N (or a smaller fraction): smoother and slowerA spike fools both averages
One glitch reads 600. avg jumps to 555 for four readings; ema jumps to 550 and fades slowly. A median of the last three readings takes the middle one, 542: the spike simply disappears.
readings 600 541 539 542 avg 555 555 555 555 ema 550 548 546 545 median 3 542 542 541 541 int median3(int a, int b, int c) { // the middle of three if ((a <= b) == (b <= c)) return b; if ((b <= a) == (a <= c)) return a; return c; }
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A moving average of 4 holds buf = [502, 497, 503, 498] and total = 2000, with i = 0. Reading 506 arrives. What is the new total?
Line 3 removes the oldest reading, buf[0] = 502, and adds the new one: 2000 − 502 + 506 = 2004. The average becomes 2004 / 4 = 501.
02Why does a ring buffer with a running total stay fast even when N is large?
Instead of adding up all N slots every time, the total is updated: subtract the reading that leaves, add the one that arrives. The cost per reading does not grow with N, though the array does.
03If the noise in each reading is random and independent, averaging 16 readings cuts it to about…
Noise falls by about the square root of the number of readings averaged: √16 = 4, so to about a quarter (Smith, ch. 15).
04The knob turns and the readings jump from about 500 to about 540. With N = 4 and one reading every 100 ms, how long until avg has fully caught up?
The average only reaches the new level once all 4 slots hold new readings: 510, 519, 531, 540. That is 4 × 100 ms = 0.4 s. A bigger N would smooth more but lag longer.
05One glitch reads 600 among readings of about 540. Which smoother ignores it completely?
The median takes the middle of three values, so a single outlier is never chosen: it stays at 542. The average of 4 jumps to 555 and ema to 550, because every reading counts in an average.
المسرد
- Noise
- Random variation in a reading that does not come from the thing being measured: interference on wires and supply, and the converter's own error.
- LSB (least significant bit)
- One step of the ADC. On the Arduino Uno R3's 10-bit ADC with a 5 V reference, one step is about 4.9 mV.
- Moving average
- The average of the last N readings, updated every time a new reading arrives.
- Ring buffer
- A fixed-size array whose write position wraps from the last slot back to the first, so the newest value overwrites the oldest.
- Running total
- A sum kept up to date by adding what arrives and subtracting what leaves, instead of adding everything again.
- Exponential moving average (EMA)
- A smoother that keeps one value and moves it a fixed fraction of the way toward each new reading; a single pole low-pass filter.
- Lag
- The delay between a real change in the input and the smoothed output reaching it.
- Median of three
- The middle value of the last three readings; it ignores a single spike.
الملاحظات والمصادر
- 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.
- avg is an int, so total / N drops the fraction (2004 / 4 = 501, not 501). total can reach 4 × 1023 = 4092, which fits in the Uno's 16-bit int; a large N needs a long.
- ema += (x − ema) / 4 is Smith's single pole low-pass filter with a0 = 1/4 and b1 = 0.75. Its time constant is about 3.5 readings. The Uno has no floating-point hardware, so float maths runs in software; integer versions use a scaled sum instead.
- Averaging cuts noise by √N only when the noise in each reading is random and independent. It cannot remove a steady offset, and the ±2 LSB accuracy of the ADC includes errors that averaging does not fix.
- The median needs the last three readings in order, so it fits a ring buffer of three. It follows a real step one reading late: at the knob turn it still says 502 once.
- Arduino: Smoothing (built-in example)
- Arduino examples source: Smoothing.ino
- Arduino language reference: analogRead() (source)
- Microchip ATmega328P datasheet (DS40002061B), ch. 24 Analog-to-Digital Converter
- S. W. Smith, The Scientist and Engineer's Guide to DSP, ch. 15: Moving Average Filters
- S. W. Smith, The Scientist and Engineer's Guide to DSP, ch. 19: Recursive Filters
- J. W. Valvano, Embedded Systems: Shape the World, ch. 14: ADC and data acquisition (UT Austin)
اختبار يتاح بعد الخطوة الأخيرة.