I have sensor data coming in on the serial port. Below is the function that displays the readings in the console window. I was wondering how could I store 10 readings in an array and store the average as a new variable?
If you the number of samples being averaged is a power of two, you can shift bits to divide the total by the number of the sample. Here are a few sections from my joystick averaging program.
A power of two quantity also makes if faster to loop the head of the ring buffer back to zero.
bufferIndex++;
bufferIndex &= BUFFER_LIMIT;
Here's some of the constants and variables which were used above. As you can see, the "BUFFER_SIZE" and "BUFFER_LIMIT" constants are dependent on the "POWER_OF_TWO_TO_AVERAGE" constant.
const long POWER_OF_TWO_TO_AVERAGE = 4; // User changeable.
// Changing "POWER_OF_TWO_TO_AVERAGE" changes several other constants.
// The constants "BUFFER_SIZE" and "BUFFER_LIMIT" are calculated based on "POWER_OF_TWO_TO_AVERAGE".
const int BUFFER_SIZE = 1 << POWER_OF_TWO_TO_AVERAGE; // Do not change.
const int BUFFER_LIMIT = BUFFER_SIZE - 1; // Do not change.
long averagingBuffer[SERVOS_IN_USE][BUFFER_SIZE];
int bufferIndex = 0;
long bufferTotal[SERVOS_IN_USE];
Of course you don't need to use a power of two as your sample size. You can easily use divide instead of shift and just set the buffer index back to zero as needed.
Using a ring buffer to average multiple samples takes a lot more resources than the "modified moving average" suggested by Archibald.