Working moving average filter. IIR filters (low pass, high pass) still have to be implemented via biquad.

Dependencies:   HIDScope biquadFilter mbed

Fork of EMG by Tom Tom

Revision:
21:3ac3c2e9d9ae
Parent:
20:97059009a491
Child:
22:d2393c670afd
--- a/main.cpp	Thu Sep 22 08:53:50 2016 +0000
+++ b/main.cpp	Fri Oct 12 13:12:31 2018 +0000
@@ -1,37 +1,58 @@
 #include "mbed.h"
+#include "BiQuad.h"
 #include "HIDScope.h"
 
 //Define objects
+HIDScope scope(2); // We’re going to send 2 channels of data
 AnalogIn    emg0( A0 );
 AnalogIn    emg1( A1 );
 
-Ticker      sample_timer;
-HIDScope    scope( 2 );
-DigitalOut  led(LED1);
+Ticker emgSampleTicker;
+
+// filter chains for high pass, low pass and notch filters
+BiQuadChain bqc;
+BiQuad bq1( 4.1660e04,8.3320e04,4.1660e04,1.4797e+00,.5582e01);
+BiQuad bq2( 1.0000e+00, 2.0000e+00, 1.0000e+00, 1.7010e+00,7.8850e01);
+volatile double y[50]= { };
+volatile int n = 0;
+volatile bool full = 0;
 
-/** Sample function
- * this function samples the emg and sends it to HIDScope
- **/
-void sample()
-{
-    /* Set the sampled emg values in channel 0 (the first channel) and 1 (the second channel) in the 'HIDScope' instance named 'scope' */
-    scope.set(0, emg0.read() );
-    scope.set(1, emg1.read() );
-    /* Repeat the step above if required for more channels of required (channel 0 up to 5 = 6 channels) 
-    *  Ensure that enough channels are available (HIDScope scope( 2 ))
-    *  Finally, send all channels to the PC at once */
+void emgSample() {
+    //double emgFiltered = bqc.step( emg0.read() );
+    double emgFiltered = emg0.read();
+    scope.set(0,emgFiltered);
+    
+    // moving average
+    y[n] = abs(emgFiltered - 0.45);
+    double emgavg = 0;
+    if(full == 0){
+        for(int i=0;i<50;i++){
+            emgavg = emgavg + y[i];
+        }
+        emgavg = emgavg/(n+1);
+    }
+    else{
+        for(int i=0;i<50;i++){
+            emgavg = emgavg + y[i];
+        }
+        emgavg = emgavg/50;    
+    }
+    n++;        
+    if(n == 50){
+        n = 0;
+        full = 1;
+    }
+    scope.set(1,emgavg);
     scope.send();
-    /* To indicate that the function is working, the LED is toggled */
-    led = !led;
+    // do stuff with filtered point emgavg
 }
 
+
 int main()
 {   
-    /**Attach the 'sample' function to the timer 'sample_timer'.
-    * this ensures that 'sample' is executed every... 0.002 seconds = 500 Hz
-    */
-    sample_timer.attach(&sample, 0.002);
-
+    bqc.add( &bq1 ).add( &bq2 );
+    emgSampleTicker.attach( &emgSample, 0.01 );
+    
     /*empty loop, sample() is executed periodically*/
     while(1) {}
 }
\ No newline at end of file