Hendrik Langer
5 years ago
3 changed files with 127 additions and 0 deletions
@ -0,0 +1,77 @@ |
|||
#include "SensorHistory.h" |
|||
|
|||
#include <Arduino.h> |
|||
|
|||
//static const char *TAG = "SensorHistory";
|
|||
|
|||
SensorHistory::SensorHistory(const int size) { |
|||
_size = size; |
|||
_values = (float*) malloc(_size * sizeof(float)); |
|||
clear(); |
|||
} |
|||
|
|||
SensorHistory::~SensorHistory() |
|||
{ |
|||
if (_values != NULL) free(_values); |
|||
} |
|||
|
|||
void SensorHistory::clear(void) { |
|||
_index = 0; |
|||
_cnt = 0; |
|||
for (int i = 0; i < _size; i++) |
|||
{ |
|||
_values[i] = 0.0; // keeps addValue simpler
|
|||
} |
|||
} |
|||
|
|||
void SensorHistory::addValue(const float value) { |
|||
if (_values == NULL) return; |
|||
|
|||
_values[_index] = value; |
|||
_index = (_index+1) % _size; |
|||
|
|||
if (_cnt < _size) _cnt++; |
|||
} |
|||
|
|||
float SensorHistory::getAverage(void) const { |
|||
if (_cnt == 0) return NAN; |
|||
float sum = 0; |
|||
for (int i = 0; i < _cnt; i++) { |
|||
sum += _values[i]; |
|||
} |
|||
return sum / _cnt; |
|||
|
|||
} |
|||
|
|||
float SensorHistory::getMin(void) const { |
|||
if (_cnt == 0) return NAN; |
|||
float min = _values[0]; |
|||
for (int i = 0; i < _cnt; i++) { |
|||
if (_values[i] < min) min = _values[i]; |
|||
} |
|||
return min; |
|||
} |
|||
|
|||
float SensorHistory::getMax(void) const { |
|||
if (_cnt == 0) return NAN; |
|||
float max = _values[0]; |
|||
for (int i = 0; i < _cnt; i++) { |
|||
if (_values[i] > max) max = _values[i]; |
|||
} |
|||
return max; |
|||
} |
|||
|
|||
float SensorHistory::getElement(int index) const { |
|||
if (_cnt == 0) return NAN; |
|||
index = (_index-1 - index) % _size; |
|||
if (index < 0) index = _size+index; |
|||
if (index >= _cnt) return NAN; |
|||
|
|||
return _values[index]; |
|||
} |
|||
|
|||
float SensorHistory::getFirst(void) const { |
|||
if (_cnt < _size) return _values[0]; |
|||
return getElement(-1); |
|||
|
|||
} |
@ -0,0 +1,26 @@ |
|||
#ifndef _SENSOR_HISTORY_H |
|||
#define _SENSOR_HISTORY_H |
|||
|
|||
class SensorHistory { |
|||
public: |
|||
explicit SensorHistory(const int); |
|||
~SensorHistory(); |
|||
void clear(); |
|||
void addValue(const float); |
|||
float getAverage() const; |
|||
float getMin() const; |
|||
float getMax() const; |
|||
float getElement(int) const; |
|||
float getFirst() const; |
|||
int getSize() const { return _size; }; |
|||
int getCount() const { return _cnt; }; |
|||
protected: |
|||
int _size; |
|||
int _index; |
|||
int _cnt; |
|||
float* _values; |
|||
}; |
|||
|
|||
|
|||
|
|||
#endif /* _SENSOR_HISTORY_H */ |
Loading…
Reference in new issue