emg

Fork of EMG by Tom Tom

Revision:
18:e753220c7ba6
Parent:
16:9f7797ffd0fb
--- a/main.cpp	Tue Sep 22 07:00:54 2015 +0000
+++ b/main.cpp	Mon Oct 19 11:44:19 2015 +0000
@@ -1,20 +1,69 @@
 #include "mbed.h"
 #include "HIDScope.h"
 
+#define MOV_AVG_NUM     100
+
 //Define objects
 AnalogIn    emg(A0); //Analog input
 Ticker      sample_timer;
-HIDScope    scope(1);
+HIDScope    scope(2);
+
+double highV[4];
+double lowV[4];
+double lastOutputs[MOV_AVG_NUM-1];
+
+double filter(double input, double coeff_input[], double coeff_output[], double prev_outputs[])
+{
+    double new_input = input;
+    for(int i=1; i<5; i++) 
+        new_input -= coeff_input[i] * prev_outputs[i-1];
+
+    double new_output = coeff_output[0] * new_input;
+    for(int i=1; i<5; i++) 
+        new_output += coeff_output[i] * prev_outputs[i-1];
+
+    // Set the new output as the first value of the 'recent outputs'
+    for(int i = 3; i > 0; i--)
+        prev_outputs[i] = prev_outputs[i-1];
+    prev_outputs[0] = new_input;
+    return new_output;
+}
+
+double fh_b[]= {0.7602, -3.0406, 4.5609, -3.0406, 0.7602};
+double fh_a[]= {1, -3.4532, 4.5041, -2.6273, 0.5778};
+double highpass_filter(double u)
+{
+    return filter(u, fh_a, fh_b, highV);
+}
+
+double fl_b[]= {0.00000658, 0.00002631, 0.00003947, 0.00002631, 0.00000658};
+double fl_a[]= {1.0000, -3.7264, 5.2160, -3.2500, 0.7605};
+double lowpass_filter(double u)
+{
+    return filter(u, fl_a, fl_b, lowV);
+}
 
 /** Sample function
  * this function samples the emg and sends it to HIDScope
  **/
 void sample()
 {
-    /* First, sample the EMG using the 'read' method of the 'AnalogIn' variable named 'emg' */
-    double emg_value = emg.read();
+    double input = emg.read();
+    double output1 = highpass_filter(input);
+    double output2 = fabs(output1);
+    double output3 = lowpass_filter(output2);
+    
+    double tot = output3;
+    for(int i=0; i<MOV_AVG_NUM-1; i++) {
+        tot += lastOutputs[i];
+        if(i != 0) lastOutputs[i] = lastOutputs[i-1];
+    }
+    lastOutputs[0] = output3;
+    output3 = tot/MOV_AVG_NUM;
+    
     /* Second, set the sampled emg value in channel zero (the first channel) in the 'HIDScope' variable named 'scope' */
-    scope.set(0,emg_value);
+    scope.set(0,input);
+    scope.set(1,output3);
     /* Repeat the step above if required for more channels (channel 0 up to 5 = 6 channels) */
     /* Finally, send all channels to the PC at once */
     scope.send();