Class for automatic handling of moving averages.

Revision:
0:332104904b69
diff -r 000000000000 -r 332104904b69 MovingAverage.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MovingAverage.h	Fri Mar 29 15:44:58 2019 +0000
@@ -0,0 +1,67 @@
+/** @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
\ No newline at end of file