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

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "math.h"
00003 #define PI 3.1415926536
00004 //#define GAIN 2.661812926e+05 // For Buttherworth
00005 #define GAIN 3.676489487e+05 // For Chebyshev
00006 
00007 // Pin  and timer setup
00008 DigitalIn b0(PTA4);
00009 Serial pc(USBTX, USBRX);
00010 Ticker samp;
00011 
00012 double in, rect, out;
00013 double xv[4], yv[4];
00014 double s2[500], s20[50];
00015 int i, i2, i20;
00016 
00017 // ISR for periodical interrupt
00018 void newsample(void) {
00019     in = s2[i2] * s20[i20];
00020     i2++;
00021     if(i2 > 499) {
00022         i2 = 0;
00023     }
00024     i20++;
00025     if(i20 > 49) i20 = 0;
00026     i++;
00027     
00028     rect = abs(in); // Full-wave rectification
00029     // The filter is low-pass IIR 3rd-order -0.5dB Chebyshev, cutoff frequency 5Hz for 1kHz samples.
00030     // Design was made through the website: http://www-users.cs.york.ac.uk/~fisher/mkfilter/
00031     xv[0] = xv[1];
00032     xv[1] = xv[2];
00033     xv[2] = xv[3]; 
00034     xv[3] = rect / GAIN;
00035     yv[0] = yv[1];
00036     yv[1] = yv[2];
00037     yv[2] = yv[3]; 
00038     //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
00039     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
00040     out = yv[3];
00041   
00042     printf("%f,%f\r\n", in, out);
00043 }
00044 
00045 void initfilter(void) {
00046     char k;
00047     for(k = 0; k < 4; k++) {
00048         xv[k] = 0;
00049         yv[k] = 0;
00050     }
00051 }
00052 
00053 // Main function
00054 int main() {
00055     initfilter();
00056     pc.baud(57600);
00057     
00058     for(i = 0; i < 50; i++) {
00059         s20[i] = sin(i*PI/25);
00060     }
00061     for(i = 0; i < 500; i++) {
00062         s2[i] = sin(i*PI/250);;
00063     }
00064     i2 = 0;
00065     i20 = 0;
00066     i = 0;
00067     while(b0); // waits for PB0 push
00068     samp.attach(&newsample, 0.01); // periodical interrupt every 10ms
00069     while(i < 5000) {
00070         //
00071     }
00072     samp.detach();
00073     
00074     while(1) {
00075     }
00076 }