I'm writing a C function to generate bandpass FIR filter coefficients using a simple window method (more details here FIR filters by windowing)
The important code snippet is the following (f1 and f2 are the low and high bandpass frequency, fs is the sampling frequency, all in hz, M is the taps number, the M coeffs are in h[0..M-1])
double* band_pass (double f1, double f2, double fs, int M) {
double* h = (double*)calloc(M,sizeof(double));
double w1 = 2.0*PI*f1/fs;
double w2 = 2.0*PI*f2/fs;
int MHALF = (M-1)/2;
for (int n=0; n<MH; n++) {
h[n] = (sin((n-MHALF)*w2) - sin((n-MHALF )*w1) ) / ((n-MHALF )*PI);
h[n] = h[n] * (0.54-0.46*cos(2*PI*n/(M-1)));
}
h[M-n-1] = h[n];
}
h[MHALF ] = (w2 - w1) / PI;
return h;
}
The coefficients (and so the filter) seem to work fine, but the gain in the bandpass isn't always unitary. I suppose I have to scale all the coefficients to obtain a unitary gain (in the bandpass).
So the question is: how do I scale the coefficients ?
Googling a bit I've found this formula for calc the BP filter gain:
gain += 2*h[n]*cos((n-MHALF)*(w1+w2)/2.);
then I have to divide all the coeffs for this gain. If it's correct, where does the formula come from and which are the formulas for the gain of the others kind of window fir filters LP, HP, bandstop ?
Thanks in advance.