Moving Average of MCP3008 (8ch ADC)

Files at this revision

API Documentation at this revision

Comitter:
ryood
Date:
Thu Oct 19 07:09:18 2017 +0000
Parent:
0:211b1b1254b3
Commit message:
bug fix

Changed in this revision

AverageMCP3008.h Show annotated file Show diff for this revision Revisions of this file
diff -r 211b1b1254b3 -r 8077de8afeb8 AverageMCP3008.h
--- a/AverageMCP3008.h	Thu Oct 12 08:45:37 2017 +0000
+++ b/AverageMCP3008.h	Thu Oct 19 07:09:18 2017 +0000
@@ -6,37 +6,45 @@
  
 class AverageMCP3008 {
 public:
-    AverageMCP3008(MCP3008* _m_p_mcp3008, int _bufferSize=8) : m_p_mcp3008(_m_p_mcp3008), bufferSize(_bufferSize), index(0) {
-        buffer = new unsigned short[bufferSize];
+    AverageMCP3008(MCP3008* _m_p_mcp3008, int _bufferSize=8) : m_p_mcp3008(_m_p_mcp3008), bufferSize(_bufferSize) {
+        buffer = new unsigned short*[8];
+        for (int i = 0; i < 8; i++) {
+            buffer[i] = new unsigned short[bufferSize];
+            index[i] = 0;
+        }
     }
     
     ~AverageMCP3008() {
+        for (int i  = 0; i < 8; i++) {
+            delete[] buffer[i];
+        }
         delete[] buffer;
     }
     
     unsigned short read_input_u16(int channel) {
-        buffer[index] = m_p_mcp3008->read_input_u16(channel);
-        index++;
-        if (index == bufferSize) {
-            index = 0;
+        channel &= 0x07;
+        buffer[channel][index[channel]] = m_p_mcp3008->read_input_u16(channel);
+        index[channel]++;
+        if (index[channel] == bufferSize) {
+            index[channel] = 0;
         }
         unsigned int sum = 0;
         for (int i = 0; i < bufferSize; i++) {
-            sum += buffer[i];
+            sum += buffer[channel][i];
         }
         return sum / bufferSize;
     }
     
     float read_input(int channel) {
         unsigned short value = read_input_u16(channel);
-        return (float)value * (1.0f / (float)0xFFFF);
+        return (float)value * (1.0f / (float)0x03FF);
     }
  
 private:
     MCP3008* m_p_mcp3008;
     int bufferSize;
-    int index;
-    unsigned short *buffer;
+    int index[8];
+    unsigned short **buffer;
 };
  
 #endif //_AVERAGE_MCP3008_H_
\ No newline at end of file