See filtering summary:LINK
Low pass filter design AN2874- application notes:LINK
Audio-EQ Coockbock:LINK
Second order recursive linear filter, containing two poles and two zeros, so called "biQuad" form LINK
#include "signal_gen.h"
#include < cmath >
#define PI 3.14159265358979323846
struct Coeff
{
double a1,a2;
double b0,b1,b2;
};
// second order butterworth filter
Coeff LPF_butter(double fc, double fs)
{ Coeff LPF;
const double ita =1.0/ tan(M_PI*fc/fs);
const double q=sqrt(2.0);
LPF.b0 = 1.0 / (1.0 + q*ita + ita*ita);
LPF.b1 = 2*LPF.b0;
LPF.b2 = LPF.b0;
LPF.a1 = -2.0 * (ita*ita - 1.0) * LPF.b0;
LPF.a2 = (1.0 - q*ita + ita*ita) * LPF.b0;
return LPF;
}
struct DEQ
{
// set up the x[n-1], x[n-2] ...
double x1,x2;
double y0,y1, y2;
double b0,b1,b2;
double a1,a2;
double process(const Coeff& fltCoeff, double x0)
{
// read in the coefficients
b0 = fltCoeff.b0;
b1 = fltCoeff.b1;
b2 = fltCoeff.b2;
a1 = fltCoeff.a1;
a2 = fltCoeff.a2;
y0 = b0*x0 + b1*x1 + b2*x2 - a1*y1 -a2*y2;
x2 = x1;
x1 = x0;
y2 = y1;
y1 = y0;
return y0;
}
};
int main()
{
std::cout << "|||||||||||||||||||||||||||||||||||||||||||||||||||||| FILTER prototype 2. \n" ;
double fs = 10e3; // 10kHz sampling frequency
DEQ sys; // difference equations
double fc = 20; // cutoff frequency ...
Coeff lpf = LPF_butter(fc,fs);
cout << "\n ";
cout << lpf.b0 << endl << lpf.b1 << endl << lpf.b2 << endl << lpf.a1 << endl << lpf.a2 << endl;
std::cout << "|||||||||||||||||||||||||||||||||||||||||||||||||||||| Generate signal Pt2. \n" ;
//|*************************************************************************************************
//| SIGNAL GENERATION
//| fs, f, Amp, phi, t_max
signal_gen signal; signal.sinus(fs,5,5,0,1);
signal_gen overTone; overTone.sinus(fs,70,2,0,1);
vector x = signal.getSignal();
vector x1 = overTone.getSignal();
vector signal_sum;
for (size_t i = 0; i < x.size(); i++) { signal_sum.push_back(x[i] + x1[i] ); }
std::cout << "|||||||||||||||||||||||||||||||||||||||||||||||||||||| Filter and Write signals . \n" ;
//| filter output ...
//|
vector yout;
for(size_t i = 0; i < signal_sum.size(); i++) {yout.push_back(sys.process(lpf, signal_sum[i]));}