clear all;
close all;
%first halfband filter
SAMP1=32;
wp1=1/2-0.25/2;
wc1=1/2+0.25/2;
%second halfband filter
SAMP2=16;
wp2=1/2-0.5/2;
wc2=1/2+0.5/2;

F1=[0,wp1,wc1,1];F2=[0,wp2,wc2,1];
A=[1,1,0,0];
N1=SAMP1*2;N2=SAMP2*2;
NX1=[0:N1];NX2=[0:N2];

h1=remez(N1,F1,A);h2=remez(N2,F2,A);
B1=real(h1);B2=real(h2);

C1=4*32768*B1*2;C2=4*32768*B2*2;
hn1=round(C1);hn2=round(C2);

figure('Name','FIR滤波器系数','NUM','off','UNITS','Normal','Pos',[0.2 0.2 .7 .7],'Color',[1 1 1]);
subplot(211);
plot(NX1,C1);
xlabel('n');
ylabel('hn');
grid;

subplot(212);
plot(NX2,C2);
xlabel('n');
ylabel('hn');
grid;

[h,w1]=freqz(hn1,1,2048);[h2,w2]=freqz(hn2,1,4096);
h1=[1:4096]';
h1(1:2048)=h;h1(2049:4096)=h(2048:-1:1);
figure('Name','量化后滤波器的实际频率特性','NUM','off','UNITS','Normal','Pos',[0.2 0.2 .7 .7],'Color',[1 1 1]);
subplot(211);
xh=w2*4*1.024/3.14159265;yh1=20*log10(abs(h1))-360*log10(2);yh2=20*log10(abs(h2))-360*log10(2);
plot(xh,yh1,xh,yh2);
xlabel('MHz');ylabel('20lg|H(exp(jw))|(dB)');
grid;
subplot(212);
plot(xh,yh1+yh2);
xlabel('MHz');ylabel('20lg|H(exp(jw))|(dB)');
grid;

fid=fopen('HBFirCof.hex','w');
fprintf(fid,'module HBFirCof(clk,Address,Data);\n');
fprintf(fid,'\tinput[4:0] Address;\n');
fprintf(fid,'\tinput clk;\n');
fprintf(fid,'\toutput [17:0] Data;\n');
fprintf(fid,'\treg [17:0] Data;\n\n');
fprintf(fid,'\talways @(posedge clk) begin\n');
fprintf(fid,'\t\tcase(Address)\n');

for m=0 : N1/4-1, 
    if hn1(N1/2-2*m)>=0
        tempv=hn1(N1/2-2*m);
    else 
       tempv=power(2,18)-abs(hn1(N1/2-2*m));
   end
    fprintf(fid,'\t\t\t5\047h%01X:Data<=18\047h%05X;\n',m,tempv);
end

for m=0 : N2/4-1, 
    if hn2(N2/2-2*m)>=0
        tempv=hn2(N2/2-2*m);
    else 
       tempv=power(2,18)-abs(hn2(N2/2-2*m));
   end
    fprintf(fid,'\t\t\t5\047h%01X:Data<=18\047h%05X;\n',m+N1/4,tempv);
end
fprintf(fid,'\t\t\tdefalut:Data<=18\047h0;\n');
fprintf(fid,'\t\tendcase\n');
fprintf(fid,'\tend\n');
fprintf(fid,'endmodule\n\n');

fclose(fid);

