%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Butterworth Analog Filter Design
% Vishal Saxena, BSU 2010
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

close all; clear all; clc;

%% Define the filter specs
% MATLAB likes angular frequency (w=2*pi*f) for design
Wp = 2*pi*1e6;      % Passband corner frequency 
Ws = 2*pi*3e6;      % Stopband corner frequency
Rp = 0.5;           % Passband ripple (dB)
Rs = 60;            % Stopband ripple (dB)

% Define simulation params
fmax = 5e6;         % Max frequency for plotting

%% Do a 'doc buttord' in MATLAB for documentation (look for 'Analog Domain')

% Find the minimum filter order 'n' and cutoff frequency (Wb)
% Notice the use of 's' option for analog filter design
[n,Wb] = buttord(Wp,Ws,Rp,Rs, 's');  

fb = Wb/(2*pi*1e6); % fB is the 3-dB bandwidth of the filter

sprintf('Minimum order of the filter, n = %d', n)
sprintf('Filter cutoff frequency, fb = %0.5g MHz', fb)

% Design a Butterworth filter with n and Wb
[z,p,k] = butter(n,Wb,'s');

% Obtain numerator and denominator coeff for the analog filter
[b,a] = zp2tf(z,p,k);

% Find analog filter response
w = linspace(0,fmax,1000)*2*pi;     % Create frequency (w) vector 
H = freqs(b,a,w);                   % Find frequency response
H_dB = 20*log10(abs(H));            % Convert to dB scale

%% Plot the filter response
figure(1)
% Normalize the x-axis to freq in MHz
plot(w/(2*pi*1e6), H_dB, 'b', 'LineWidth', 2); 
grid on, hold on; 
xlim([0 fmax/1e6]);
title('Butterworth LP Filter Design', 'FontWeight', 'bold');
xlabel('Frequency (MHz)'); ylabel('Magnitude (dB)');
text(fb, -3, '\leftarrow f_{3-dB}','HorizontalAlignment','left',...
    'Color', 'red', 'FontWeight', 'bold')
% EOF
