%=========UFSC - Federal University of Santa Catarina========
% Author: Tiago Davi Curi Busarello
% Date: Feburary 2019
% Project: Design of a digital current controller of a STATCOM. This file
% is part of the paper   of the paper Three-Phase STATCOM with digital 
% control strategy and in abc reference frame, publisehd in 2020 3rd 
% International Conference on Computing, Mathematics and Engineering 
% Technologies (iCoMET).

close all
clear all
clc
format long

f = 60; 
T = 1/f;
Vdc = 1000; 
Lf = 10e-3;
Rf = 0.001;
Hi = 1/10;
Fs = 30e3;
fc = Fs/10;
MFd = 55;

ts = 1/Fs;

tstart = 0.15; %moment where the statcom begins to work

s = tf('s');
Gi = Vdc / (s*Lf + Rf);

FTMAu = Gi*Hi;

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

figure
bode(FTMAu,opts)
title('Uncontrolled Open Loop Transfer Function');
xlim([0.001 1e5]);
grid

%Design of the type 2 current controller
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/2 + 45);

Prod = 1/(2*pi*fc*ganho_real*K2);
C2 = 100e-9;
R1 = Prod/C2;
C1 = C2*((K2^2)-1);
R2 = K2/(2*pi*fc*C1);


Ctipo2 = (1+s*R2*C1)/(s*R1*(C1+C2+s*R2*C1*C2));

figure
bode(Ctipo2,opts)
title('Designed controller');
xlim([0.001 1e5]);
grid

FTMAc = FTMAu*Ctipo2;
figure
bode(FTMAc,opts)
xlim([0.001 1e5]);
title('Controlled Open Loop Transfer Function');
grid

inst2 = evalfr(FTMAc, 2*pi*fc*j);
MF_obitda = rad2deg(phase(inst2))+180;

ganho_obtido = mag2db(abs(inst2));
ganho_real_obitdo = 10^(abs(ganho_obtido/20));

%Discretization of type 2 controller

beta = 4*R1*R2*C1*C2 + 2*ts*R1*(C1+C2);

b0 = (ts^2 + 2*ts*C1*R2)/beta;
b1 = (2*ts^2)/beta;
b2 = (ts^2 - 2*ts*C1*R2)/beta;

a0 = 1;
a1 = (-8*R1*R2*C1*C2)/beta;
a2 = (4*R1*R2*C1*C2 - 2*ts*R1*(C1+C2))/beta;

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

H = tf(b,a,ts);

figure
bode(H,opts)
hold
bode(Ctipo2,opts)
grid
title('Comparison between the analog and digital controllers');

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


bsec = b;
asec = a;

bter = b;
ater = a;

%Controle de tensão do Link CC
K = 250;
Time = 0.1;
Cvdc = K*(1+s*Time)/(s*Time);

%Discretização do controlador do link CC

b0_dc = K*(1+ts/Time);
b1_dc = -K;

a0_dc = 1;
a1_dc = -1;

b_dc = [b0_dc b1_dc];
a_dc = [a0_dc a1_dc];

Hdc = tf(b_dc,a_dc,ts);

figure
bode(Hdc,opts)
xlim([0.001 1e5]);
hold
bode(Cvdc,opts)
xlim([0.001 1e5]);
grid
title('Comparison between the analog and digital controllers of the DC-link');







