A test for a digital envelope detector using a rectifier and a low-pass filter. The program first creates sample vectors for sinusoidal waves of 2Hz and 20Hz (considering 1kHz sampling frequency). Then, every 10ms it generates a new sample for a modulated wave (multiply both waves), and passes it through a full-wave rectifier and a Chebyshev low-pass filter with cutoff frequency of 5Hz. Then it sends the original wave and the recovered envelope through serial port in CSV format. I used 10ms interval instead of 1ms because otherwise the serial speed would have to be too high.

Dependencies:   mbed

main.cpp

Committer:
quevedo
Date:
2014-08-26
Revision:
0:1ba9469c839f

File content as of revision 0:1ba9469c839f:

#include "mbed.h"
#include "math.h"
#define PI 3.1415926536
//#define GAIN 2.661812926e+05 // For Buttherworth
#define GAIN 3.676489487e+05 // For Chebyshev

// Pin  and timer setup
DigitalIn b0(PTA4);
Serial pc(USBTX, USBRX);
Ticker samp;

double in, rect, out;
double xv[4], yv[4];
double s2[500], s20[50];
int i, i2, i20;

// ISR for periodical interrupt
void newsample(void) {
    in = s2[i2] * s20[i20];
    i2++;
    if(i2 > 499) {
        i2 = 0;
    }
    i20++;
    if(i20 > 49) i20 = 0;
    i++;
    
    rect = abs(in); // Full-wave rectification
    // The filter is low-pass IIR 3rd-order -0.5dB Chebyshev, cutoff frequency 5Hz for 1kHz samples.
    // Design was made through the website: http://www-users.cs.york.ac.uk/~fisher/mkfilter/
    xv[0] = xv[1];
    xv[1] = xv[2];
    xv[2] = xv[3]; 
    xv[3] = rect / GAIN;
    yv[0] = yv[1];
    yv[1] = yv[2];
    yv[2] = yv[3]; 
    //yv[3] = xv[0] + xv[3] + 3 * (xv[1] + xv[2]) + (0.9390989403 * yv[0]) + (-2.8762997235 * yv[1]) + (2.9371707284 * yv[2]); // For Butterworth
    yv[3] = xv[0] + xv[3] + 3 * (xv[1] + xv[2]) + (0.9614041736 * yv[0]) + (-2.9213338983 * yv[1]) + (2.9599079648 * yv[2]); // For Chebyshev
    out = yv[3];
  
    printf("%f,%f\r\n", in, out);
}

void initfilter(void) {
    char k;
    for(k = 0; k < 4; k++) {
        xv[k] = 0;
        yv[k] = 0;
    }
}

// Main function
int main() {
    initfilter();
    pc.baud(57600);
    
    for(i = 0; i < 50; i++) {
        s20[i] = sin(i*PI/25);
    }
    for(i = 0; i < 500; i++) {
        s2[i] = sin(i*PI/250);;
    }
    i2 = 0;
    i20 = 0;
    i = 0;
    while(b0); // waits for PB0 push
    samp.attach(&newsample, 0.01); // periodical interrupt every 10ms
    while(i < 5000) {
        //
    }
    samp.detach();
    
    while(1) {
    }
}