format long
clear all
close all
clc

Vi=216;
Vo=127;
fs=30e3;
Hv=1/200;
fs = 30000;
ts = 1/fs;

Lf = 4.5e-3;
Cf = 100e-6;
Rf = 25;
Ro = 1000;

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

fr = (1/(2*pi))*sqrt(1/(Lf*Cf));

Xc = 1/(s*Cf);
Zeq = Rf + Xc;

figure
bode(Xc,opts);
hold 
bode(Zeq,opts);
grid
title('Effect of the Passive Damping');

Gv = (Vi*(1+s*Cf*Rf))/((s^2*(Cf*Lf + Lf*Cf*Rf/Ro) + s*(Lf/Ro + Cf*Rf) + 1));
H = Hv;

FTMAu = H*Gv;

fc = fs/10;
MFd = 60;

inst = evalfr(FTMAu, 2*pi*fc*j);
fase_fc = rad2deg(phase(inst));

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

alpha = MFd - fase_fc - 90;

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

C2 = 100e-9;
R1 = 1/(2*pi*fc*ganho_real*C2);
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('Bode da FT de malha fechada');
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)
hold
bode(Cv)
% bode(Cz)
grid
title('Comparison between the analog and digital controllers');







