Sub topic 11
Why readings jitter and how to average them
This chapter assumes you can wire a potentiometer to A0, read it with analogRead(), and print values to the Serial Monitor. It also assumes you know the 10-bit range (0 to 1023) and the 5 V reference of an Arduino Uno. Here you will see why a steady knob still produces changing numbers, how to measure that jitter, and how to reduce it by averaging.
What jitter looks like
Leave the potentiometer untouched and print the readings. You will usually see something like this:
512
513
512
511
512
514
512The knob did not move, but the values change by one to three counts. This is jitter. It is normal for analog input, and it does not mean your wiring is broken. One count on a 5 V Uno is about 4.9 mV (5 / 1023), so a jitter of two or three counts corresponds to only 10 to 15 mV of uncertainty.
The jitter matters when you use the value to make decisions. A threshold comparison can flip back and forth. An LED driven by analogWrite() can flicker. A value shown on a display can flicker too.
Where the noise comes from
Several sources add small errors to each reading.
- Electrical noise on the supply. The reference voltage on an Uno is normally the 5 V supply. If USB power ripples by a few millivolts, every reading shifts with it.
- Noise picked up by wires. Long jumper wires act as small antennas. They pick up interference from motors, relays, mains wiring, and nearby switching circuits.
- Quantization. The ADC rounds the true voltage to the nearest step. If the true voltage sits close to the boundary between two steps, tiny disturbances push the result back and forth between neighbouring values.
- Sampling effects in the ADC. The AVR ADC uses a small internal capacitor that must charge to the input voltage before conversion. A source with high impedance charges it more slowly and less completely.
- The potentiometer itself. The wiper contact is mechanical. Dust, wear, and a loose breadboard contact all change the resistance slightly.
Quantization deserves a closer look. Suppose the true voltage is 2.5000 V. On a 5 V reference, the exact reading would be 2.5000 / 5 × 1023 = 511.5. That sits exactly between steps 511 and 512, so any tiny disturbance moves the output between the two. This is why the knob can seem unstable at one position and rock solid at another.
Measuring the jitter
Before you fix something, measure it. The sketch below takes 200 readings and reports the minimum, maximum, and spread. Leave the knob alone while it runs.
const int POT_PIN = A0;
const int NUM_READINGS = 200;
void setup() {
Serial.begin(9600);
}
void loop() {
int minValue = 1023;
int maxValue = 0;
for (int i = 0; i < NUM_READINGS; i++) {
int value = analogRead(POT_PIN);
if (value < minValue) minValue = value;
if (value > maxValue) maxValue = value;
delay(5);
}
Serial.print("min=");
Serial.print(minValue);
Serial.print(" max=");
Serial.print(maxValue);
Serial.print(" spread=");
Serial.println(maxValue - minValue);
}A spread of 2 to 4 counts is typical on a breadboard with a short wire. If you see a spread of 20 or more, look at the wiring first. Check that the potentiometer's outer legs go to 5 V and GND, that the wiper goes to A0, and that every jumper sits firmly in the breadboard.
The same measurement tells you whether a fix worked. Run it before and after each change and compare the spread.
Averaging many readings
Averaging is the simplest software fix. If the errors are random, with some readings too high and others too low, they partly cancel when you add them up. The average lands closer to the true value than a single reading does.
const int POT_PIN = A0;
const int NUM_SAMPLES = 10;
int readAveraged() {
long sum = 0;
for (int i = 0; i < NUM_SAMPLES; i++) {
sum += analogRead(POT_PIN);
delay(2);
}
return sum / NUM_SAMPLES;
}
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(readAveraged());
delay(50);
}Three details in this code are worth understanding.
sumis along. On an Uno anintis 16 bits and holds at most 32767. Ten readings of 1023 add up to 10230, which fits. With 40 samples the total could reach 40920 and overflow. Alongis 32 bits and avoids the problem.- The
delay(2)between samples. Readings taken back to back are correlated. Noise that lasts a few milliseconds appears in all of them and does not cancel. A short gap lets the samples be more independent. - Integer division.
sum / NUM_SAMPLESdiscards the remainder. An average of 511.9 becomes 511. This is fine for most uses, but you can addNUM_SAMPLES / 2to the sum before dividing to round to the nearest value.
How much does averaging help?
For random, independent noise, the noise in the average shrinks in proportion to the square root of the number of samples. The table shows the effect.
| Samples averaged | Noise reduction factor | Time cost at 2 ms spacing |
|---|---|---|
| 1 | 1× (none) | about 0.1 ms |
| 4 | 2× | about 8 ms |
| 16 | 4× | about 32 ms |
| 64 | 8× | about 128 ms |
| 256 | 16× | about 512 ms |
Each doubling of precision costs four times as many samples, so returns diminish quickly. Ten samples is a good starting point for a knob that controls brightness or volume. If you need more, ask whether the noise is really random. Averaging does not remove a steady offset, and it does not fix a bad connection.
The analogRead() call itself takes about 100 microseconds on an Uno (the default ADC clock gives roughly 9600 readings per second). The delay() calls dominate the cost, so the time column above is mostly the spacing you choose.
Trade-offs of averaging
Averaging has a cost, and you should choose it with the application in mind.
- Delay. The loop spends 20 ms reading ten samples with 2 ms spacing. During that time it cannot do other work. For a sketch that also reads buttons or updates a display, this blocking behaviour can make the program feel sluggish.
- Lag. An average of the last ten readings responds more slowly to a fast change than a single reading does.
- Lost detail. If the real signal changes quickly, such as audio, averaging blurs it. Averaging suits slow signals such as a knob.
Because of these costs, use the smallest number of samples that gives a steady value.
A moving average without blocking
You can avoid the blocking delay() calls by keeping a running window of recent readings. Each pass through loop() takes one new reading, replaces the oldest one in the window, and reports the mean.
const int POT_PIN = A0;
const int WINDOW = 8;
int readings[WINDOW];
int index = 0;
long total = 0;
void setup() {
Serial.begin(9600);
int first = analogRead(POT_PIN);
for (int i = 0; i < WINDOW; i++) {
readings[i] = first;
}
total = (long)first * WINDOW;
}
void loop() {
total -= readings[index];
readings[index] = analogRead(POT_PIN);
total += readings[index];
index = (index + 1) % WINDOW;
int average = total / WINDOW;
Serial.println(average);
delay(10);
}The setup code fills the window with the first reading. Without that step, the empty array holds zeros and the first few averages would be wrong. The running total means each pass does a constant amount of work, no matter how large the window is.
The window of 8 gives a noise reduction of about 2.8×. It also introduces a lag of roughly half the window length, here about four loop passes.
Other ways to reduce jitter
Software is not the only option. Hardware changes often work better and cost nothing in processing time.
- Shorten the wires. Use short jumpers and keep them away from motors and power wiring.
- Add a capacitor. A 100 nF ceramic capacitor between A0 and GND filters fast noise at the pin.
- Use a lower-impedance source. The AVR datasheet recommends a source impedance of about 10 kΩ or less. A 10 kΩ potentiometer is right at that limit, so a 1 kΩ to 10 kΩ range works better than a 100 kΩ one.
- Discard the first reading after switching pins. When you read several analog pins in sequence, the ADC input multiplexer needs time to settle. A throwaway
analogRead()before the real one can reduce crosstalk between channels. - Stabilize the supply. Powering the board from a clean source reduces ripple on the reference.
Common mistakes
- Using an
intfor the sum and overflowing it when you raise the sample count. - Taking samples with no gap and expecting noise to cancel.
- Averaging, then multiplying the result by a large factor. This enlarges the remaining noise as well.
- Dividing by the wrong number after changing
NUM_SAMPLESin one place but not another. Use the constant in both places, as the examples do. - Forgetting to prefill a moving-average window.
How the pieces fit together
Averaging reduces the spread but does not eliminate it. A small amount of flicker can remain when the true value sits near a step boundary. The next chapter covers the deadband, a technique that ignores changes smaller than a chosen threshold so the output stays still until the knob really moves.
Summary
- Jitter of one to a few counts is normal on a 10-bit ADC.
- Sources include supply ripple, wire pickup, quantization, and the pot's wiper contact.
- Measure the min, max, and spread before changing anything.
- Averaging N independent readings cuts random noise by about the square root of N.
- Use a
longfor the sum, space the samples by a couple of milliseconds, and keep the sample count as low as the application allows. - A moving average avoids blocking delays but adds lag.
- Fix wiring and add a small capacitor before reaching for more software.
Exercise
A sketch averages 16 analogRead() samples taken with no delay between them, and the jitter barely improves. Give two reasons this might happen and one change for each.
Show answer
First, samples taken back to back share the same short-term noise, so the errors do not cancel. Add a delay of a couple of milliseconds between samples. Second, the noise may come from a bad connection or from a high-impedance source rather than random noise, so averaging cannot remove it. Check the wiring, shorten the wires, or add a 100 nF capacitor from A0 to GND.
Exercise
You average 64 samples instead of 16 to reduce noise. By what factor does the random noise fall compared with the 16-sample average, and roughly how much longer does one reading take if samples are spaced 2 ms apart?
Show answer
Noise falls with the square root of the sample count. The square root of 64 is 8 and the square root of 16 is 4, so noise falls by a factor of 2. The reading takes four times as long, about 128 ms instead of 32 ms.
Exercise
Why does the moving-average sketch fill the readings array with the first reading in setup()?
Show answer
Global arrays start filled with zeros. Without prefilling, the first several averages would include those zeros and report values far below the real reading. Filling the window with the first reading makes the average correct from the first pass.