write a first order pll in matlab in matlab

To implement a first order PLL in MATLAB, you can follow the steps below:

  1. Define the system parameters
main.m
fc = 1000;           % Carrier frequency in Hz
fs = 100000;         % Sampling frequency in Hz
Kp = 2*pi*10;        % Phase detector gain
Kv = 1;              % VCO gain
K1 = Kv/Kp;          % Transfer function constant
K2 = Kv*fc/fs*2*pi;  % Transfer function constant
zeta = 0.7;          % Damping ratio
307 chars
8 lines
  1. Generate the input signal and introduce phase noise
main.m
t = linspace(0, 1, fs);        % Generate time vector
x = cos(2*pi*fc*t + 0.2);      % Generate carrier signal
n = randn(size(t))*0.1;        % Generate phase noise
y = cos(2*pi*fc*t + 0.2 + n);  % Add noise to carrier signal
226 chars
5 lines
  1. Implement the PLL loop filter
main.m
num = [K2 K2*zeta];
den = [1 2*zeta*K2 K2^2];
lpf = tf(num, den);
66 chars
4 lines
  1. Implement the phase detector and VCO
main.m
phi = angle(y);                  % Phase of the input signal
phi_d = [phi(2:end) phi(end)];   % Delayed phase of the input signal
e = phi_d - phi;                 % Phase error
vco = tf([Kv], [1 0]);           % VCO transfer function
234 chars
5 lines
  1. Simulate the PLL loop
main.m
sim('PLL_sim');
16 chars
2 lines
  1. Plot the results
main.m
figure;
subplot(2, 1, 1);
plot(t, y);
hold on;
plot(t, vout);
xlabel('Time (s)');
ylabel('Amplitude');
legend('Input signal', 'Output signal');
subplot(2, 1, 2);
plot(t, phi);
hold on;
plot(t, phi_filtered);
xlabel('Time (s)');
ylabel('Phase');
legend('Input phase', 'Filtered phase');
286 chars
16 lines

The complete MATLAB code would be as follows:

main.m
% System parameters
fc = 1000;           % Carrier frequency in Hz
fs = 100000;         % Sampling frequency in Hz
Kp = 2*pi*10;        % Phase detector gain
Kv = 1;              % VCO gain
K1 = Kv/Kp;          % Transfer function constant
K2 = Kv*fc/fs*2*pi;  % Transfer function constant
zeta = 0.7;          % Damping ratio

% Input signal with phase noise
t = linspace(0, 1, fs);
x = cos(2*pi*fc*t + 0.2);
n = randn(size(t))*0.1;
y = cos(2*pi*fc*t + 0.2 + n);

% Loop filter
num = [K2 K2*zeta];
den = [1 2*zeta*K2 K2^2];
lpf = tf(num, den);

% Phase detector and VCO
phi = angle(y);
phi_d = [phi(2:end) phi(end)];
e = phi_d - phi;
vco = tf([Kv], [1 0]);

% Simulation
sim('PLL_sim');

% Plot results
figure;
subplot(2, 1, 1);
plot(t, y);
hold on;
plot(t, vout);
xlabel('Time (s)');
ylabel('Amplitude');
legend('Input signal', 'Output signal');
subplot(2, 1, 2);
plot(t, phi);
hold on;
plot(t, phi_filtered);
xlabel('Time (s)');
ylabel('Phase');
legend('Input phase', 'Filtered phase');
990 chars
46 lines

gistlibby LogSnag