added https://playground.arduino.cc/Main/RunningAverage
[Arduino] / wlan_si / RunningAverage.cpp
1 //
2 //    FILE: RunningAverage.cpp
3 //  AUTHOR: Rob Tillaart
4 // VERSION: 0.2.04
5 // PURPOSE: RunningAverage library for Arduino
6 //
7 // The library stores the last N individual values in a circular buffer,
8 // to calculate the running average.
9 //
10 // HISTORY:
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
19 //
20 // Released to the public domain
21 //
22
23 #include "RunningAverage.h"
24 #include <stdlib.h>
25
26 RunningAverage::RunningAverage(int n)
27 {
28     _size = n;
29     _ar = (float*) malloc(_size * sizeof(float));
30     if (_ar == NULL) _size = 0;
31     clear();
32 }
33
34 RunningAverage::~RunningAverage()
35 {
36     if (_ar != NULL) free(_ar);
37 }
38
39 // resets all counters
40 void RunningAverage::clear()
41 {
42     _cnt = 0;
43     _idx = 0;
44     _sum = 0.0;
45     for (int i = 0; i< _size; i++) _ar[i] = 0.0;  // needed to keep addValue simple
46 }
47
48 // adds a new value to the data-set
49 void RunningAverage::addValue(float f)
50 {
51     if (_ar == NULL) return;
52     _sum -= _ar[_idx];
53     _ar[_idx] = f;
54     _sum += _ar[_idx];
55     _idx++;
56     if (_idx == _size) _idx = 0;  // faster than %
57     if (_cnt < _size) _cnt++;
58 }
59
60 // returns the average of the data-set added sofar
61 float RunningAverage::getAverage()
62 {
63     if (_cnt == 0) return NAN;
64     return _sum / _cnt;
65 }
66
67 // returns the value of an element if exist, 0 otherwise
68 float RunningAverage::getElement(uint8_t idx)
69 {
70     if (idx >=_cnt ) return NAN;
71     return _ar[idx];
72 }
73
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)
78 {
79     clear();
80     for (int i = 0; i < number; i++)
81     {
82         addValue(value);
83     }
84 }
85 // END OF FILE