1 //
2 // firdespm_lowpass_example.c
3 //
4 // This example demonstrates a low-pass finite impulse response filter
5 // design using the Parks-McClellan algorithm.
6 //
7 // SEE ALSO: firdes_kaiser_example.c
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <getopt.h>
12 #include <math.h>
13
14 #include "liquid.h"
15
16 #define OUTPUT_FILENAME "firdespm_lowpass_example.m"
17
18 // print usage/help message
usage()19 void usage()
20 {
21 printf("firdespm_lowpass_example:\n");
22 printf(" -h : print usage/help\n");
23 printf(" -n <len> : filter length, 1 < n default: 57\n");
24 printf(" -f <freq> : filter cutoff frequency, 0 < f < 0.5, default: 0.2\n");
25 printf(" -s <atten>: stop-band attenuation [dB], 0 < s, default: 60\n");
26 }
27
main(int argc,char * argv[])28 int main(int argc, char*argv[]) {
29 // options
30 unsigned int n = 57; // filter cutoff frequency
31 float fc = 0.2f; // filter cutoff frequency
32 float As = 60.0f; // stop-band attenuation [dB]
33
34 int dopt;
35 while ((dopt = getopt(argc,argv,"hn:f:s:")) != EOF) {
36 switch (dopt) {
37 case 'h': usage(); return 0;
38 case 'n': n = atoi(optarg); break;
39 case 'f': fc = atof(optarg); break;
40 case 's': As = atof(optarg); break;
41 default: return -1;
42 }
43 }
44 unsigned int i;
45 printf("filter design parameters\n");
46 printf(" length : %12u\n", n);
47 printf(" cutoff frequency : %12.8f Fs\n", fc);
48 printf(" stop-band attenuation : %12.3f dB\n", As);
49
50 // design the filter
51 float h[n];
52 firdespm_lowpass(n,fc,As,0,h);
53
54 #if 0
55 // print coefficients
56 for (i=0; i<n; i++)
57 printf("h(%4u) = %16.12f;\n", i+1, h[i]);
58 #endif
59
60 // open output file
61 FILE*fid = fopen(OUTPUT_FILENAME,"w");
62 fprintf(fid,"%% %s : auto-generated file\n", OUTPUT_FILENAME);
63 fprintf(fid,"clear all;\n");
64 fprintf(fid,"close all;\n\n");
65 fprintf(fid,"h_len=%u;\n", n);
66 fprintf(fid,"fc=%12.4e;\n",fc);
67 fprintf(fid,"As=%12.4e;\n",As);
68
69 for (i=0; i<n; i++)
70 fprintf(fid,"h(%4u) = %20.8e;\n", i+1, h[i]);
71
72 fprintf(fid,"nfft=1024;\n");
73 fprintf(fid,"H=20*log10(abs(fftshift(fft(h,nfft))));\n");
74 fprintf(fid,"f=[0:(nfft-1)]/nfft-0.5;\n");
75 fprintf(fid,"figure; plot(f,H,'Color',[0 0.5 0.25],'LineWidth',2);\n");
76 fprintf(fid,"grid on;\n");
77 fprintf(fid,"xlabel('normalized frequency');\n");
78 fprintf(fid,"ylabel('PSD [dB]');\n");
79 fprintf(fid,"title(['Filter design (firdespm) f_c: %.3f, S_L: %.3f, h: %u']);\n",
80 fc, -As, n);
81 fprintf(fid,"axis([-0.5 0.5 -As-20 10]);\n");
82
83 fclose(fid);
84 printf("results written to %s.\n", OUTPUT_FILENAME);
85
86 printf("done.\n");
87 return 0;
88 }
89
90