Moving Average Analog In

Dependents:   BSM02

Files at this revision

API Documentation at this revision

Comitter:
ryood
Date:
Tue Jun 21 05:19:31 2016 +0000
Commit message:
Moving Average Analog In;

Changed in this revision

AverageAnalogIn.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r abe0f7520f24 AverageAnalogIn.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/AverageAnalogIn.h	Tue Jun 21 05:19:31 2016 +0000
@@ -0,0 +1,41 @@
+#ifndef _AVERAGE_ANALOG_H_
+#define _AVERAGE_ANALOG_H_
+
+#include "mbed.h"
+
+class AverageAnalogIn {
+public:
+    AverageAnalogIn(PinName _pin, int _bufferSize=8) : m_AnalogIn(_pin), bufferSize(_bufferSize), index(0) {
+        buffer = new unsigned short[bufferSize];
+    }
+    
+    ~AverageAnalogIn() {
+        delete[] buffer;
+    }
+    
+    unsigned short read_u16() {
+        buffer[index] = m_AnalogIn.read_u16();
+        index++;
+        if (index == bufferSize) {
+            index = 0;
+        }
+        unsigned int sum = 0;
+        for (int i = 0; i < bufferSize; i++) {
+            sum += buffer[i];
+        }
+        return sum / bufferSize;
+    }
+    
+    float read() {
+        unsigned short value = read_u16();
+        return (float)value * (1.0f / (float)0xFFFF);
+    }
+
+private:
+    AnalogIn m_AnalogIn;
+    int bufferSize;
+    int index;
+    unsigned short *buffer;
+};
+
+#endif //_AVERAGE_ANALOG_H_
\ No newline at end of file