emg

Dependencies:   HIDScope mbed

Fork of EMG by Kevin Hetterscheid

Revision:
19:34c129b055b6
Parent:
18:e753220c7ba6
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/emg.cpp	Tue Oct 20 08:00:52 2015 +0000
@@ -0,0 +1,80 @@
+#include "mbed.h"
+#include "HIDScope.h"
+#include "emg.h"
+
+//Define objects
+AnalogIn    emg(A0); //Analog input
+Ticker      sample_timer;
+HIDScope    scope(2);
+
+double highV[4];
+double lowV[4];
+// An array which stores the last MOV_AVG_NUM outputs
+double lastOutputs[MOV_AVG_NUM-1];
+// The sum of the last MOV_AVG_NUM outputs
+double outputSum;
+
+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);
+}
+
+void sample()
+{
+    double input = emg.read();
+    double output1 = highpass_filter(input);
+    double output2 = fabs(output1);
+    double output3 = lowpass_filter(output2);
+    
+    /* Calculate the average of the last MOV_AVG_NUM outputs and the new input */
+    outputSum = outputSum - lastOutputs[MOV_AVG_NUM-2] + output3;
+    for(int i=0; i<MOV_AVG_NUM-1; i++) {
+        if(i != 0) lastOutputs[i] = lastOutputs[i-1];
+    }
+    lastOutputs[0] = output3;
+    output3 = outputSum/MOV_AVG_NUM;
+    
+    /* Second, set the sampled emg value in channel zero (the first channel) in the 'HIDScope' variable named 'scope' */
+    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();
+}
+
+/*
+int main()
+{
+    //Attach the 'sample' function to the timer 'sample_timer'. this ensures that 'sample' is executed every... 0.002 seconds
+
+    sample_timer.attach(&sample, 0.002);
+
+    //empty loop, sample() is executed periodically
+    while(1) {}
+}*/
\ No newline at end of file