Efficient Moving Average for Microcontrollers
The brute force way to compute this is to repeat the computation for every new data point. This requires that N data points are stored, and N-1 additions are computed with a single divide.
Another way to update the moving average is to merely subtract x[i-N-1]/N and to add x[i]/N to the current MA. This requires 2 additions and 2 divisions, but still this requires that N data points be saved.
The following method doesn't require any storage of previous data values, and minimizes divisions which are computationally intensive. It works by subtracting out the mean each time, and adding in a new point.
MA*[i]= MA*[i-1] +X[i] - MA*[i-1]/N
where MA* is the moving average*N.
The advantage of this technique is that previous data values need not be stored. If N is a power of 2 the division can be accomplished with a computationally efficient shift. So a single division and subtraction and 2 shifts are all that are needed, rendering suitable for a simple microcontroller.
Daycounter specializes in contract electronics design. Do you need some help on your project? Contact us to get a quote.
Salt Lake City, UT, USA
Disclaimer: Daycounter, Inc. doesn't guarantee the accuracy of any of it's content. Use at your own risk.