How to store serial data in array and get average

Hi,

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?

void showNewData() {
if (newData == true) {
char* reading = receivedChars + 1;
sensorReading = atoi(reading);
Serial.println(reading);

newData = false;
}
}

Many thanks

Do you really need to do that? You could add the readings to the previous ten times and then divide the total by ten.

oh yes that would be easier thanks

Nick_Pyner:
Do you really need to do that? You could add the readings to the previous ten times and then divide the total by ten.

If you are describing use of a modified moving average, you would add the new reading to nine times the previous average and divide the total by ten.

That's not the same as averaging the most recent ten readings.

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.

      averageJoystickInput = bufferTotal[servoIndex] >> POWER_OF_TWO_TO_AVERAGE;

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.