2 // FILE: RunningAverage.cpp
3 // AUTHOR: Rob Tillaart
5 // PURPOSE: RunningAverage library for Arduino
7 // The library stores the last N individual values in a circular buffer,
8 // to calculate the running average.
11 // 0.1.00 - 2011-01-30 initial version
12 // 0.1.01 - 2011-02-28 fixed missing destructor in .h
13 // 0.2.00 - 2012-??-?? Yuval Naveh added trimValue (found on web)
14 // http://stromputer.googlecode.com/svn-history/r74/trunk/Arduino/Libraries/RunningAverage/RunningAverage.cpp
15 // 0.2.01 - 2012-11-21 refactored
16 // 0.2.02 - 2012-12-30 refactored trimValue -> fillValue
17 // 0.2.03 - 2013-11-31 getElement
18 // 0.2.04 - 2014-07-03 added memory protection
20 // Released to the public domain
23 #include "RunningAverage.h"
26 RunningAverage::RunningAverage(int n)
29 _ar = (float*) malloc(_size * sizeof(float));
30 if (_ar == NULL) _size = 0;
34 RunningAverage::~RunningAverage()
36 if (_ar != NULL) free(_ar);
39 // resets all counters
40 void RunningAverage::clear()
45 for (int i = 0; i< _size; i++) _ar[i] = 0.0; // needed to keep addValue simple
48 // adds a new value to the data-set
49 void RunningAverage::addValue(float f)
51 if (_ar == NULL) return;
56 if (_idx == _size) _idx = 0; // faster than %
57 if (_cnt < _size) _cnt++;
60 // returns the average of the data-set added sofar
61 float RunningAverage::getAverage()
63 if (_cnt == 0) return NAN;
67 // returns the value of an element if exist, 0 otherwise
68 float RunningAverage::getElement(uint8_t idx)
70 if (idx >=_cnt ) return NAN;
74 // fill the average with a value
75 // the param number determines how often value is added (weight)
76 // number should preferably be between 1 and size
77 void RunningAverage::fillValue(float value, int number)
80 for (int i = 0; i < number; i++)