% Digital Audio Course 
% © 2014 Prof. Mario Malcangi

% Infinite Impulse Response (IIR) Low-Pass Filter
%
% y(n) = ax(n)+by(n-1) 1st order (-6dB)
% a=1-exp(-2*pi*(Fc/Fs));
% b=1-a;
% 

clear;
close all;

Fs=8000;    % Sampling rate

% ---------------------------------------------------------------

% Pattern to test the filter frequency response
% Sequence of pure tones

D=500;      % Pattern duration (samples)
f0=500;     % Step frequency

f=0;
k=1;
while f<Fs/2 % Stop when frequency is higher than half of sampling rate   
    for n=1:D  % Generate a D-length segment of the pattern
        x(k)=sin(2*pi*n*f/Fs);
        k=k+1;
    end
    f=f+f0; % Step the frequency
end

% ----- IIR filter setup --------------------------------------------------

N=length(x);            % Total samples of the pattern

Fc=1000;                % Cutoff frequency (Hz)
a=1-exp(-2*pi*(Fc/Fs)); % First filter coefficent
b=1-a;                  % Second filter coefficent
 
% ----------- IIR filter core ---------------------------------------------

y(1)=0;       % Filter memory (starts as zero)
n=2;  
while n < N   % Run the filter for all input samples
    y(n)=a*x(n)+b*y(n-1);
    n=n+1;
end 

% Show how input is filtered
% Check that cutoff frequency is down by -3dB (0.707)
% Check that each octave after cutoff frequency is down by -6dB (0.5)
% Check that all frequencies befor cutoff frequency are always not down 
% more then -3dB

subplot(2,1,1)
plot(x);
legend('Filter Input');
subplot(2,1,2)
plot(y);
legend('Filter Output');


  
