% lab7.m
%
% Matlab script to create Bode plot of frequency response for band-pass
% filter.
% Rich Kozick, ELEC 225

% This program is for an RLC band-pass filter with analytical frequency response
% H(w) = R / ((R+r) + j*(w*L - 1/(w*C)))

% Define circuit element values 
R = 20;   % Ohms
C = 0.68e-6;  % Farads
L = 10e-3;  % Henrys
r = 0;  % Resistance of inductor

f0 = 1/sqrt(L*C)/(2*pi);
fprintf('Resonant frequency = %f Hz\n', f0);

% Create a vector of frequency values in Hz to evaluate the response.
% Space them logarithmically to create a Bode plot.

f = logspace(2, 5, 500);	% Hz, from 10^2 to 10^8 with 500 points
w = 2*pi*f;			% frequency in radians/sec

H = R ./ ((R+r) + j*(w*L - 1./(w*C)));	% Complex response, use ./ to divide vectors
Mag = abs(H);			% Magnitude or amplitude gain

figure(1)
semilogx(f, Mag, 'k-');
title('Frequency Response Magnitude')
xlabel('Frequency (Hz)');
ylabel('Gain');
grid   % Remove this line to turn off grid lines

% Comment out the next line to plot measured data
return

% To compare measured data with analytical frequency response, both can
% be plotted on the same graph.
% Suppose you have 4 measured values (you will have more than 4 in lab):

f_meas = [200, 1594, 1935, 2414, 20e3];
Vin = [1, 1, 1, 1, 1];  % Input voltage amplitude
Vout = [.01, 0.4, 0.99, 0.34, 0.02];  % Output voltage amplitude
Mag_meas = Vout ./ Vin;

figure(2)
semilogx(f, Mag, 'k-', f_meas, Mag_meas, 'ko');
legend('Analytical', 'Measured')
title('Frequency Response Magnitude')
xlabel('Frequency (Hz)');
ylabel('Gain');
grid
