Class for automatic handling of moving averages.

MovingAverage.h

Committer:
fbcosentino
Date:
2019-03-29
Revision:
0:332104904b69

File content as of revision 0:332104904b69:

/** @file MovingAverage.h
 *  A moving average filter class for analog-to-digital converters.
 *  This version uses static memmory allocation. Not RAM optimized
 *  but increases device compatibility avoiding malloc calls.
 *
 *  @author Fernando Cosentino
 */

#ifndef __MOVINGAVERAGE
#define __MOVINGAVERAGE

#define _MA_FIFO_SIZE 65 // must be sample size + 1

/**
 * Helper class implementing a float FIFO.
 */
class _ma_fifo
{
    float buffer[_MA_FIFO_SIZE];
    unsigned int head, tail;

public:
    _ma_fifo();
    int put(float data);// returns 0 on success
    int get(float * data);
    int available();
    int free();
};

/**
 * Receives a constant stream of samples and outputs the last available
 * average. The value is in the past by half the number of averaged samples.
 */
class MovingAverage {
public:
    /**
     * Creates an instance of the MovingAverage class.
     *
     * @param number_of_samples Number of samples to average per output value.
     * Maximum value is 64.
     */
    MovingAverage(int number_of_samples);
    
    /**
     * Inserts a new value into the filter, and returns the updated average.
     *
     * @param value The new value to be inserted.
     * @returns The updated average including the new value.
     */
    float filter(float value);

private:
    _ma_fifo _samples;
    int _started;
    int _num_samples;
    float _average;
    

};







#endif