Fernando Cosentino / MovingAverage
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers MovingAverage.cpp Source File

MovingAverage.cpp

00001 #include "MovingAverage.h"
00002 
00003 MovingAverage::MovingAverage(int number_of_samples) {
00004     _started = 0;
00005     _average = 0.0;
00006     _num_samples = number_of_samples;
00007 }
00008 
00009 float MovingAverage::filter(float value) {
00010     // If this filter has already started, means we have other samples
00011     if (_started) {
00012         float dropping_value;
00013         if (_samples.get(&dropping_value) == 0) { // if no errors
00014             // if value == dropping_value, average is kept the same
00015             _average = _average + ((value - dropping_value) / _num_samples);
00016             _samples.put(value);
00017         }
00018     }
00019     // If we are starting now, this sample is all we have
00020     else {
00021         // fills the buffer with the initial value
00022         for (int i=0; i < _num_samples; i++) _samples.put(value);
00023         _started = 1;
00024         _average = value; // Average is the initial value.
00025     }
00026     return _average;
00027 }
00028 
00029 
00030 
00031 // FIFO HELPER CLASS
00032 
00033 _ma_fifo::_ma_fifo() {
00034     head = 0;
00035     tail = 0;
00036 }
00037 int _ma_fifo::available() {
00038     return (_MA_FIFO_SIZE + this->head - this->tail) % _MA_FIFO_SIZE;
00039 }
00040 int _ma_fifo::free() {
00041     return (_MA_FIFO_SIZE - 1 - available());
00042 }
00043 int _ma_fifo::put(float data) {
00044     int next;
00045     // check if FIFO has room
00046     next = (head + 1) % _MA_FIFO_SIZE;
00047     if (next == tail) return 1; // fifo full
00048 
00049     buffer[head] = data;
00050     head = next;
00051     return 0;
00052 }
00053 int _ma_fifo::get(float * data) {
00054     int next;
00055     // check if FIFO has data
00056     if (head == tail) return 1; // FIFO empty
00057 
00058     next = (tail + 1) % _MA_FIFO_SIZE;
00059     *data = buffer[tail];
00060     tail = next;
00061     return 0;
00062 }