EMG_filter zonder moving average

Dependencies:   HIDScope mbed

Fork of EMG by Kevin Hetterscheid

main.cpp

Committer:
AeroKev
Date:
2015-10-19
Revision:
18:e753220c7ba6
Parent:
16:9f7797ffd0fb
Child:
19:105e719a8aa5

File content as of revision 18:e753220c7ba6:

#include "mbed.h"
#include "HIDScope.h"

#define MOV_AVG_NUM     100

//Define objects
AnalogIn    emg(A0); //Analog input
Ticker      sample_timer;
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()
{
    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,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) {}
}