%=========UFSC - Federal University of Santa Catarina========
% Author: Tiago Davi Curi Busarello
% Date: 2021
% Project: Control Strategy based on Frequency Response for 
% a Single-Phase Full-Bridge Series Active Filter
% 
% Published in 16th Brazilian Power Electronics Conference 2021


format long
clear all
close all

Vi=450;
Vo=220;
fsw=20e3;
Hv=1/311;
fs = 20e3;
ts = 1/fs;
Vtri = 1; %Amplitude of the carrier 

Lf = 2.2e-3;
Cf = 220e-6;
Ro = 10000;

s = tf('s');
opts = bodeoptions('cstprefs');
opts.FreqUnits = 'Hz';

Ginv = Vi; %Inverter gain
Gv = Ginv/((Lf*Cf*s^2) + (Lf/Ro)*s + 1);
H = Hv;

td = 1/(1.5*fs);
Delay = -(s-(2/td))/(s+(2/td));
% Delay = 1; %needs to change line fase_fc

FTMAu = H*Gv*Delay/Vtri;
FT = H*Gv*Delay/Vtri;

fc = fsw/10;
MFd = 55;

inst = evalfr(FTMAu, 2*pi*fc*j);
fase_fc = rad2deg(phase(inst));
fase_fc = fase_fc - 360;  %This line is needed only because the consideration of the delay

ganho_fc = mag2db(abs(inst));
ganho_real = 10^(abs(ganho_fc/20));

alpha = MFd - fase_fc - 90;

K2 = (tand(alpha/4 + 45))^2;

R1 = 1000;
C2 = 1/(2*pi*fc*ganho_real*R1);
C1 = C2*(K2-1);
R2 = sqrt(K2)/(2*pi*fc*C1);
R3 = R1/(K2-1);
C3 = 1/(2*pi*fc*R3*sqrt(K2));

Cv = (s^2*R2*C1*C3*(R1+R3) + s*(R2*C1+R1*C3+R3*C3)+1) /(s^3*R1*R2*R3*C1*C2*C3 + s^2*(R1*R3*C3*(C1+C2)+R1*R2*C1*C2)+s*R1*(C1+C2));

FTMAc = FTMAu*Cv;
figure
bode(FTMAu,opts);
title('Bode da FT de malha aberta sem controle');
hold 
bode(FTMAc,opts)
title('Bode da FT de malha aberta com controle');
bode(Cv,opts)
title('Bode da FT do controlador projetado');
grid

FTMF = FTMAc/(FTMAc + 1);
figure 
bode(FTMF,opts)
title('Closed-Loop Bode Diagram');
grid

%Discretização do tipo 3

D1 = R2*C1*C3*(R1+R3);
D2 = R2*C1 + R1*C3 + R3*C3;
D3 = R1*R2*R3*C1*C2*C3;
D4 = R1*R3*C1*(C1+C2) + R1*R2*C1*C2;
D5 = R1*(C1+C2);

Dcte = D3+D4*ts+D5*ts^2;

b0 = (ts*D1 + D2*ts^2 + ts^3)/Dcte;
b1 = -(2*ts*D1 + D2*ts^2)/Dcte;
b2 = D1*ts/Dcte;
b3 = 0;

a0 = 1;
a1 = -(3*D3+2*D4*ts+D5*ts^2)/Dcte;
a2 = (3*D3+D4*ts)/Dcte;
a3 = -D3/Dcte;

b = [b0 b1 b2 b3];
a = [a0 a1 a2 a3];

H = tf(b,a,ts);

figure 
margin(FTMAc)
grid

% Alternatively

% Cz = c2d(Cv,ts,'tustin');
% [num,den] = tfdata(Cz,'v');
 
% b = num;
% a = den;

figure
bode(H,opts)
hold
bode(Cv,opts)
% bode(Cz)
grid
title('Anlog and Digital Controllers');


%Analysing the capacitor and the transformer
Lm = 500e-6;
L1 = 100e-6;

XL = 2*pi*50*(L1+Lm)*s;
XC = 1/(2*pi*50*Cf*s);

Zeq = (XL*XC)/(XL+XC);

figure
bode(XC,opts)
hold
bode(Zeq,opts)
grid






