%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function: PLLmain.m
% Programmed by: Qian Wang
% Date: September 20, 2006
% Version: 1.0
% Description: This simulation program is to genterate input parameters
%              for PLL and process the results.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear all;

%********************** Parameters ***************************

fs     = 44.1*1e3;                        %Sampling rate
K_pd   = 1;                               %Phase detector gain
K_vco  = 2*pi*1e1;                        %VCO gain
tyofpd = 1;                               %Type of phase detector (1 = Multiplier; 2 = XOR)
f_vco  = 1e3;                             %VCO center frequency
f_in   = f_vco + 10;                        %Frequency of input signal

M = 1;
N = 1;
%********************** Signal input *************************

t      = 0:1/fs:2;                        %Simulation time
sig_in = sin(2*pi*f_in*t);                %Generate input signal
% sig_in = square(2*pi*f_in*t);

%********************** Loop filter design *************************

%Parameter design
w_vco = 2*pi*f_vco;
w_3db = 0.05*w_vco;
w_T   = w_3db/1.33;
w2    = w_T/sqrt(10);
w3    = w_T*sqrt(10);
T1    = (K_vco*K_pd/(sqrt(10)*w2^2));
T2    = 1/w2;
T3    = 1/w3;

num = [T2 1];                             %Numerator of loop filter transfer function
den = [T1*T3 T1 0];                       %Denominator of loop filter transfer function

%********************** PLL function part *************************

[vco_out,pd_out,lf_out,phi_vco] = PLL(sig_in,fs,num,den,K_vco,K_pd,tyofpd,f_vco,M,N);

%********************** Postprocesser part ***************************

figure(1);
plot(t,pd_out(1:length(t)));
figure(2);
plot(t,lf_out(1:length(t)));
figure(3);
plot(t,vco_out(1:length(t)));
grid on
hold on;
plot(t,sig_in,'r');
hold off;
figure(4);
plot(t,vco_out(1:length(t)) + sig_in);
% subplot(1,2,1),plot(t,lf_out(1:length(t))),
% xlabel('t (s)'),ylabel('Output signal of loop filter')
% subplot(1,2,2),plot(t,vco_out(1:length(t)) + sig_in),
% xlabel('t (s)'),ylabel('Combination of input and output signal')
%%%%%%%%%%%%%%%%%%%%%% end of file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
