Class for automatic handling of moving averages.
Diff: MovingAverage.cpp
- Revision:
- 0:332104904b69
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/MovingAverage.cpp Fri Mar 29 15:44:58 2019 +0000 @@ -0,0 +1,62 @@ +#include "MovingAverage.h" + +MovingAverage::MovingAverage(int number_of_samples) { + _started = 0; + _average = 0.0; + _num_samples = number_of_samples; +} + +float MovingAverage::filter(float value) { + // If this filter has already started, means we have other samples + if (_started) { + float dropping_value; + if (_samples.get(&dropping_value) == 0) { // if no errors + // if value == dropping_value, average is kept the same + _average = _average + ((value - dropping_value) / _num_samples); + _samples.put(value); + } + } + // If we are starting now, this sample is all we have + else { + // fills the buffer with the initial value + for (int i=0; i < _num_samples; i++) _samples.put(value); + _started = 1; + _average = value; // Average is the initial value. + } + return _average; +} + + + +// FIFO HELPER CLASS + +_ma_fifo::_ma_fifo() { + head = 0; + tail = 0; +} +int _ma_fifo::available() { + return (_MA_FIFO_SIZE + this->head - this->tail) % _MA_FIFO_SIZE; +} +int _ma_fifo::free() { + return (_MA_FIFO_SIZE - 1 - available()); +} +int _ma_fifo::put(float data) { + int next; + // check if FIFO has room + next = (head + 1) % _MA_FIFO_SIZE; + if (next == tail) return 1; // fifo full + + buffer[head] = data; + head = next; + return 0; +} +int _ma_fifo::get(float * data) { + int next; + // check if FIFO has data + if (head == tail) return 1; // FIFO empty + + next = (tail + 1) % _MA_FIFO_SIZE; + *data = buffer[tail]; + tail = next; + return 0; +} \ No newline at end of file