create phase locked loop code in matlab

main.m
% Define the parameters of the Phase-Locked Loop (PLL)
f_cl = 1000; % Desired closed-loop bandwidth
N = 100; % Number of samples
t = 0:1/N:1-1/N;
noise_power = 0.1;
Kpd = 20; % Proportional gain
Kid = 300; % Integral gain
Fs = 2000; % Sampling frequency

% Generate a noisy reference signal
ref_signal = cos(2*pi*100*t) + sqrt(noise_power)*randn(1,N);

% Initialize variables
theta = zeros(1,N);
theta_hat = zeros(1,N);
theta_dot = zeros(1,N);
theta_dot_hat = zeros(1,N);
e = zeros(1,N);
e_dot = zeros(1,N);

% Loop through each sample index
for k = 2:N
    % Compute error signal
    e(k) = ref_signal(k) - cos(theta(k-1));
    
    % Compute the phase detector output signal
    delta = e(k)*sin(theta(k-1));
    
    % Compute the loop filter output signal
    a = Kpd + Kid/Fs;
    theta_dot(k) = a*delta;
    
    % Update the phase
    theta(k) = theta(k-1) + theta_dot(k)/Fs;
    
    % Generate the estimated angle using the VCO
    % (same as theta(k-1) + Kp*error_signal)
    theta_hat(k) = theta(k-1) + a*e(k);
    
    % Compute the error derivative
    e_dot(k) = (ref_signal(k) - cos(theta_hat(k)))*sin(theta_hat(k));
    
    % Update the integral terms
    Kid = Kid + e(k)/Fs;
end

% Plot the results
figure;
subplot(3,1,1);
plot(t,ref_signal,'b',t,cos(theta),'r','LineWidth',1.5);
xlabel('Time (s)');
ylabel('Signal');
legend('Input Signal','PLL Output');
title('Phase-Locked Loop Simulation');

subplot(3,1,2);
plot(t,e,'r','LineWidth',1.5);
xlabel('Time (s)');
ylabel('Error');
title('Error Signal');

subplot(3,1,3);
plot(t,theta_dot,'r','LineWidth',1.5);
xlabel('Time (s)');
ylabel('Theta Dot');
title('Phase Detector Output');
1650 chars
67 lines

Above is an example implementation of a phase-locked loop (PLL) in MATLAB. This code simulates a PLL system and plots the input signal, PLL output, error signal, and phase detector output.

main.m
0 chars
1 lines

gistlibby LogSnag