Running average

This commit is contained in:
Rob Tillaart 2011-10-09 22:24:50 +02:00
parent b5205149a5
commit 7191f93920
4 changed files with 145 additions and 0 deletions

View File

@ -0,0 +1,57 @@
//
// FILE: RunningAverage.cpp
// AUTHOR: Rob Tillaart
// VERSION: 0.1.01
// PURPOSE: RunningAverage library for Arduino
//
// The library does store the last N individual values, to
// calculate the running average.
//
// HISTORY:
// 0.1.00 - 2011-01-30 initial version
// 0.1.01 - 2011-02-28 fixed missing destructor in .h
//
// Released to the public domain
//
#include "RunningAverage.h"
#include <stdlib.h>
RunningAverage::RunningAverage(int n)
{
_size = n;
_ar = (float*) malloc(_size * sizeof(float));
clr();
}
RunningAverage::~RunningAverage()
{
free(_ar);
}
// resets all counters
void RunningAverage::clr()
{
_cnt = 0;
_idx = 0;
_sum = 0.0;
for (int i=0; i< _size; i++) _ar[i] = 0.0;
}
// adds a new value to the data-set
void RunningAverage::add(float f)
{
_sum -= _ar[_idx];
_ar[_idx] = f;
_sum += _ar[_idx];
_idx = (_idx + 1) % _size;
if (_cnt < _size) _cnt++;
}
// returns the average of the data-set added sofar
float RunningAverage::avg()
{
return _sum / _cnt;
}
// END OF FILE

View File

@ -0,0 +1,33 @@
#ifndef RunningAverage_h
#define RunningAverage_h
//
// FILE: RunningAverage.h
// AUTHOR: Rob dot Tillaart at gmail dot com
// PURPOSE: RunningAverage library for Arduino
// VERSION: 0.1.01
// URL: http://arduino.cc/playground/Main/RunningAverage
// HISTORY: See RunningAverage.cpp
//
// Released to the public domain
//
class RunningAverage
{
public:
RunningAverage(void);
RunningAverage(int);
~RunningAverage();
void clr();
void add(float);
float avg();
protected:
int _size;
int _cnt;
int _idx;
float _sum;
float * _ar;
};
#endif
// END OF FILE

View File

@ -0,0 +1,28 @@
#include "RunningAverage.h"
RunningAverage raMinute(60);
RunningAverage raHour(60);
int samples = 0;
void setup(void)
{
Serial.begin(115200);
Serial.println("Demo RunningAverage lib - average per minute & hour");
raHour.clr();
raMinute.clr();
}
void loop(void)
{
long rn = random(0, 100);
raMinute.add(rn);
samples++;
if (samples % 60 == 0) raHour.add(raMinute.avg());
Serial.print(" raMinute: ");
Serial.print(raMinute.avg(), 4);
Serial.print(" raHour: ");
Serial.println(raHour.avg(), 4);
}

View File

@ -0,0 +1,27 @@
#include "RunningAverage.h"
RunningAverage myRA(10); // use default size
int samples = 0;
void setup(void)
{
Serial.begin(115200);
Serial.println("Demo RunningAverage lib");
myRA.clr(); // explicitly start clean
}
void loop(void)
{
long rn = random(0, 100);
myRA.add(rn/100.0);
samples++;
Serial.print("Running Average: ");
Serial.println(myRA.avg(), 4);
if (samples == 300)
{
samples = 0;
myRA.clr();
}
delay(100);
}