Nominal Animal
Well-known member
No, just once (gauge_value).I will have to sample the data twice in each loop, correct?
Think of gauge_shown as the needle in the gauge, dragged around by the sampled gauge_value , but limited to a maximum rate of change.
If the sampled value jitters, and you want to smooth that out, you'll need to instead implement a smoothing filter.
The two most commonly used filtering schemes for this sort of stuff are exponential and windowed.
Exponential is the simplest, but may take some experimentation to find the optimum coefficient. The code itself is trivial:
Code:
#define GAUGE_COEFFICIENT 0.75 /* between 0.5 and 1 */
gauge_shown = GAUGE_COEFFICIENT * gauge_value + (1.0f - GAUGE_COEFFICIENT) * gauge_shown;
The optimum GAUGE_COEFFICIENT depends on the amount of jitter, and how rapidly the shown gauge should react to large changes. The smaller, the smoother; the closer to one, the faster it reacts.
Windowed filtering involves keeping a short queue of sampled values, always replacing the oldest one with the new sample, and showing their average:
Code:
#define GAUGE_SAMPLES 20
float gauge_sample[GAUGE_SAMPLES];
unsigned int gauge_sample_index = 0;
int i;
/* Add a new sample */
gauge_sample[gauge_sample_index++] = gauge_value;
if (gauge_sample_index >= GAUGE_SAMPLES)
gauge_sample_index = 0;
/* Calculate average */
gauge_shown = 0.0f;
for (i = 0; i < GAUGE_SAMPLES; i++)
gauge_shown += gauge_sample[i];
gauge_shown /= GAUGE_SAMPLES;
The window size also determines the amount of latency (delay in registering a change) the shown gauge has.
For example, if the samples are first all zeroes, and then suddenly change to one, it takes GAUGE_SAMPLES updates before the shown gauge gets to one. It will rise there linearly.
Sometimes the window is also weighted, but I would guess that in this kind of application the exponential filter will work better (than a weighted windowing filter).