Electronic – arduino – Help with delayed smoothing code

arduinocode

I'm hung up on how to smooth analog sensor data in a specific way. Math/code is not my expertise so thanks in advance.

My sketch needs to listen an AnalogPin and smooth/remove any outliers as the values change, though smoothly settle on the final AnalogPin value.

Ex. if the sensor is a Mic in an empty room and over 30-60 seconds the room fills with people, I'd need a MicValue that slowly grows to the new volume but omits any initial foot steps or major peaks.

Ex. if the AnalogRead pin is a potentiometer, rapidly rotating the knob for 5 seconds wouldn't have much effect, but where the knob ends up the value would slowly settle upon.

Any help to define what I am looking for, or help with code would be greatly appreciated. Thanks!

Best Answer

A simple smoothed estimator can be obtained simply by a linear blending of the newly sampled value and the existing smoothed value:

smoothed_value := (1 - alpha) * smoothed_value + alpha * new_value

For instance if alpha is 0.20 (20%), then we have:

smoothed_value = 0.8 * smoothed_value + 0.2 * new_value

In other words, take 80% of the existing value, and 20% of the new sample.

By doing some algebraic manipulation, we can show that it can also be calculated this way:

smoothed_value := smoothed_value + alpha * (new_value - smoothed_value)

In other words, update the smoothed value by adding to it just the alpha fraction of the step between it and the new value.

If you make everything integer, and use a power of two for alpha or a multiple of a power of two, you can do this very efficiently on even unsophisticated processors that don't support multiplication or division. For instance, suppose we want to make alpha 3/16. In C, we can do the multiply by 3 and divide by 16 with shifts and adds:

delta = new_value - smoothed_value
smoothed_value += ((delta << 1) + delta) >> 4;

This type of smoothing exhibits exponential decay. It is similar to processes in nature such as, oh, the way an RC circuit charges or discharges to track changes in the applied voltage.

The alpha parameter is in the range [0, 1]. If it is zero, the new values are ignored; there is no convergence. If it is 1, then smoothed_value isn't smoothed at all; it follows new_value instantly. Low values close to zero provide slow convergence.

This algorithm, or something very similar, is used in the TCP protocol to establish a basis for the retransmission time-out based on measurements of the connection round-trip time.