Sub topic 12
Ignoring small changes with a deadband
This chapter assumes you can already read the potentiometer with analogRead(), print values to the Serial Monitor, and average several samples as in the previous chapter. You should also be comfortable with map() and analogWrite(). Here you add a second filter: a deadband, which makes your sketch act only when the input has changed by a meaningful amount.
Why averaging is not enough
Averaging reduces random jitter, but it does not remove it. A potentiometer wired to a 10-bit ADC (analog-to-digital converter) on a breadboard commonly flickers between two or three neighboring values even when nobody touches the knob. With ten-sample averaging the flicker shrinks, but a value can still sit on the boundary between two steps and flip back and forth.
That flicker causes real problems:
- The Serial Monitor scrolls with lines that carry no information.
- An LED display or an LCD redraws constantly and may visibly flicker.
- Code that triggers an action on every change, such as writing to EEPROM, sending a network message, or moving a servo, runs far more often than it should.
- Writing to EEPROM wears the memory out, because each cell tolerates a limited number of writes.
A deadband solves this by defining a zone around the last accepted value in which new readings are ignored. The reading has to leave that zone before your program treats it as a real change.
What a deadband is
A deadband is a range of input change that produces no response. In this chapter it works like this:
- Keep a variable,
lastReported, holding the last value your program accepted. - Take a new reading.
- Compute the absolute difference between the new reading and
lastReported. - If the difference is smaller than a threshold, ignore the reading.
- If the difference is at least the threshold, accept it and store it as the new
lastReported.
The threshold is the width of the deadband, measured in ADC steps. Control engineers use the same word for a zone around a setpoint where a controller does nothing. Here the zone is centered on the last accepted value and moves each time you accept a reading.
The basic sketch
This is the minimal version. It prints a value only when it moves at least THRESHOLD steps from the last printed value.
const int POT_PIN = A0;
const int THRESHOLD = 4;
int lastReported = -1;
void setup() {
Serial.begin(9600);
}
void loop() {
int value = analogRead(POT_PIN);
if (lastReported < 0 || abs(value - lastReported) >= THRESHOLD) {
lastReported = value;
Serial.println(value);
}
delay(20);
}Three details matter here.
- The sentinel value.
lastReportedstarts at-1, whichanalogRead()can never return. The testlastReported < 0guarantees the first reading is always accepted. Without it, a pot resting near 0 would never print its starting position. - The comparison uses
>=. A change of exactlyTHRESHOLDsteps counts as a real change. Using>makes the effective deadband one step wider than the constant suggests. lastReportedonly updates on acceptance. This is the part people most often get wrong, and the next section covers it.
The most common bug: updating the reference every loop
Suppose you write the filter like this:
int value = analogRead(POT_PIN);
if (abs(value - lastReported) >= THRESHOLD) {
Serial.println(value);
}
lastReported = value; // wrong: runs on every passNow you compare each reading to the previous reading, not to the last accepted one. If you turn the knob slowly, each step between two loop passes may be only 1 or 2 counts. No single pass crosses the threshold, so nothing prints, even though the knob has moved by hundreds of counts overall. The filter hides slow, deliberate movement, which is the opposite of what you want.
Keep the reference fixed until you accept a new value. Then slow turns eventually accumulate a difference of THRESHOLD from the reference and get reported.
Choosing a threshold
The threshold trades stability against resolution. On an Uno with a 5 V reference, one ADC step is about 4.89 mV (5 / 1023).
| Threshold (steps) | Approximate voltage change | Approximate distinct reported values | Typical use |
|---|---|---|---|
| 1 | 4.9 mV | about 1023 | No real filtering, since one step is the smallest change |
| 4 | 19.6 mV | about 255 | General purpose, removes most single-step flicker |
| 8 | 39 mV | about 128 | Noisy breadboard setups, menu selection |
| 16 | 78 mV | about 64 | Coarse controls, long wires |
To choose a value, print raw readings with the pot untouched and note how far they wander. Set the threshold just above that wander. A threshold much larger than the noise throws away resolution you paid for.
A deadband also adds a small lag in one direction. After you reverse the knob, the reading must travel the full threshold before anything is reported. For a volume control this is invisible. For a precision instrument it may not be acceptable, and you should keep the threshold small.
Combining averaging, a deadband, and output
In a real sketch you usually apply both filters in sequence. Averaging removes fast random noise, and the deadband suppresses what remains. The sketch below also drives an LED on PWM pin 9, as in the earlier chapter, and only updates the output when the accepted value changes.
const int POT_PIN = A0;
const int LED_PIN = 9;
const int NUM_SAMPLES = 8;
const int THRESHOLD = 4;
const int ADC_MAX = 1023;
int lastReported = -1;
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() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int value = readAveraged();
bool atEnd = (value == 0 || value == ADC_MAX);
bool moved = abs(value - lastReported) >= THRESHOLD;
if (lastReported < 0 || moved || (atEnd && value != lastReported)) {
lastReported = value;
analogWrite(LED_PIN, map(value, 0, ADC_MAX, 0, 255));
Serial.println(value);
}
delay(10);
}Notice that readAveraged() is called once and stored in value. The deadband logic then uses that single stored number everywhere.
The endpoint problem
The extra atEnd condition in the sketch above fixes a subtle flaw in a plain deadband. Suppose the last accepted value was 3 and you turn the knob fully to its end, where the reading is 0. The difference is 3, which is less than a threshold of 4. The filter ignores it, so your program never sees 0. The LED stays faintly lit at brightness 0 or 1 when it should be fully off, and a volume control never reaches silence.
The fix is to always accept the extreme values when they differ from the last accepted one. The condition (atEnd && value != lastReported) does that. The second half prevents the filter from re-reporting 0 on every pass once it has been accepted.
Gotchas with abs()
On Arduino, abs() is a macro, not a true function. A macro pastes its argument into the expression, so the argument can be evaluated more than once. That makes this line dangerous:
if (abs(analogRead(POT_PIN) - lastReported) >= THRESHOLD) { ... }Depending on how the macro expands, analogRead() may run twice, and the two calls can return different numbers. Always read into a variable first, as every sketch in this chapter does, and pass only plain variables to abs().
Other points to watch:
- Keep the compared values as
int. If you store them asunsigned int, subtracting a larger number from a smaller one wraps around to a huge positive value, and the filter fires constantly. - Do not shrink the
delay()to nothing when averaging. The short pause between samples gives the ADC's sample-and-hold capacitor time to settle, and the averaged result is more stable. - If several pots share one ADC, as on every Uno, keep one
lastReportedper pot. A single shared variable makes the channels interfere with each other. Use an array indexed by channel.
Deadband versus other approaches
You have now seen three tools for steadying a reading. They do different jobs.
- Averaging reduces random noise in the number itself. It costs time, since you take several samples per reading.
- A deadband decides whether a number is worth acting on. It leaves the number untouched but hides small changes.
- Reducing resolution, such as mapping to 0 to 255 with integer math, behaves like a built-in deadband. The output only changes when the input crosses a step boundary. It still flickers when the input sits right on a boundary, which is why an explicit deadband is more reliable.
If you compare in output units instead, for example brightness from 0 to 255, a threshold of 1 or 2 output steps works as a deadband that scales with your range. Pick the units that match what your program cares about.
Summary of the technique
- Initialize
lastReportedto-1. - Read, and average if needed, into a single variable.
- Accept the reading when it is the first one, when it differs from
lastReportedby at least the threshold, or when it hits an endpoint that has not been reported. - Update
lastReportedonly on acceptance. - Do all expensive work, such as printing, drawing, or writing storage, only inside the acceptance branch.
Exercise
A sketch uses THRESHOLD = 5 and lastReported = 500. The pot is turned slowly so that the readings on consecutive loop passes are 501, 502, 503, 504, 505. At which reading does the filter accept a value, and what would happen if lastReported were updated on every pass instead?
Show answer
The filter accepts 505, because abs(505 - 500) = 5 meets the threshold of 5 with >=. If lastReported were updated on every pass, each comparison would be against the previous reading and the difference would always be 1, so nothing would ever be accepted however far the knob turned.
Exercise
With THRESHOLD = 4, the last accepted value is 2. The knob is turned fully to one end and the reading becomes 0. Why does the basic deadband never report 0, and what condition fixes it?
Show answer
The difference abs(0 - 2) = 2 is less than 4, so the reading is ignored and 0 is never reported. Add an endpoint check: accept the reading if value is 0 or 1023 and value != lastReported. The second part stops the same endpoint from being reported on every loop pass.
Exercise
On an Uno with a 5 V reference, roughly how many millivolts does a threshold of 8 steps correspond to?
Show answer
One step is 5 / 1023, about 4.89 mV, so 8 steps is about 39 mV.