Skip to content

Instantly share code, notes, and snippets.

@mrcodetastic
Created August 13, 2020 16:11
Show Gist options
  • Save mrcodetastic/3fd6394c5d6294c993d8b42b026578da to your computer and use it in GitHub Desktop.
Save mrcodetastic/3fd6394c5d6294c993d8b42b026578da to your computer and use it in GitHub Desktop.
Rolling Moving Average in C
#ifndef MOVING_AVERAGE_H
#define MOVING_AVERAGE_H
#define ROLLING_AVERAGE_WINDOW 6
// Light Sensor (analogue read) - Moving average
int maverage_values[ROLLING_AVERAGE_WINDOW] = {0}; // all are zero as a start
int maverage_current_position = 0;
long maverage_current_sum = 0;
int maverage_sample_length = sizeof(maverage_values) / sizeof(maverage_values[0]);
// From: https://gist.github.com/bmccormack/d12f4bf0c96423d03f82
/*
int movingAvg(int *ptrArrNumbers, long *ptrSum, int pos, int len, int nextNum)
{
//return movingAvg(maverage_values, &maverage_current_sum, maverage_current_position, maverage_sample_length, current_maverage_reading);
//Subtract the oldest number from the prev sum, add the new number
*ptrSum = *ptrSum - ptrArrNumbers[pos] + nextNum;
//Assign the nextNum to the position in the array
ptrArrNumbers[pos] = nextNum;
//return the average
return *ptrSum / len;
}
*/
// Updated
int RollingmAvg(int newValue)
{
//Subtract the oldest number from the prev sum, add the new number
maverage_current_sum = maverage_current_sum - maverage_values[maverage_current_position] + newValue;
//Assign the newValue to the position in the array
maverage_values[maverage_current_position] = newValue;
maverage_current_position++;
if (maverage_current_position >= maverage_sample_length) { // Don't go beyond the size of the array...
maverage_current_position = 0;
}
//return the average
return maverage_current_sum / maverage_sample_length;
}
#endif
@Jason-buaa
Copy link

It works. Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment