%=========University of Vaasa========
% Author: Tiago Davi Curi Busarello
% Date: February 2023
% Project: Three-phase Inverter with Voltage Controller in dq-rotating
% reference frame

clear all
close all
format long
clc 

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

%---------------------------System Parameters----------------------------
Urms = 230; %Output voltage per phase in RMS
f = 50; %Output frequency
Po = 5500; %Output power per phase
VDC = 800; %DC-link Voltage
Fsw = 10e3; %Switching Frequency in Hz
Fs = Fsw; %Sampling Frequency in Hz
Ts = 1/Fs; %Sampling Period in seconds
Ro = 1000; %Fictitious load
Hv = 0.00823; %Voltage sensor gain
Hi = 0.606; %Sensor gain
Rg = 0.001; %grid resistance
Lg = 600e-6; %grid inductance
Hvcc = 1/800; %DC-link voltage sensor gain
Ccc= 12e-3; %Capacitance of the DC-link

%--------------------Load and Output Filter------------------------------
Ro_nom = (Urms^2/(Po/3)); %Output resistor (load) for nominal power
IL=Urms/Ro_nom; %Average current through inductor
deltaIL=0.15*IL; %Current variation in the inductor current assuming 15%

Ro_nom = Ro_nom; %Adopted value
Po_Ro = Urms^2/Ro_nom; %Power of the load resistor

Lmin=VDC/(4*Fsw*deltaIL); %Minumum allowed inductance
fco=1000; %Desired cut-off frequency for the output filter
Cmin=(1/Lmin)*((1/(2*pi*fco))^2); %Minumum allowed capacitance

L=Lmin;
C=Cmin;

RL=0.02;

% L=12e-3; %adopted value due to availability in the lab
% C=6e-6; %adopted value due to availability in the lab

fres = (1/(2*pi))*sqrt(1/(L*C)); %Resonant frequency of LC filter
Zfilter = 1/(s^2*L*C+1);  %Transfer function of the LC filter

Rd = 1/(2*pi*fres*C);

%------------------------Design of AC Voltage and Current Control----------------------
tau_i = 0.125e-3;    %Desired time constant of the current controller
kp_i = L/tau_i;
ki_i = RL/tau_i;

z = (1/tau_i)/10;
wc = sqrt(z/tau_i);
k_v = C*wc;

%------------------------Design of DC-link Voltage Control----------------------
tau_vdc = 0.0125e-3
Cvdc=-(2/C)*((tau_vdc*s+1)/s)
b0_vdc = (2/C)*tau_vdc
b1_vdc= (2/C)

%-------------------Plots--------------------------
% figure
% subplot(2,2,1);
% bode(Zfilter,opts)
% title('Frequency response of the LC filter')
% grid

% subplot(2,2,2);
% bode(OLTFc,opts)
% grid
% 
% subplot(2,2,3);
% bode(Cv,opts)
% title('CLTF');
% grid
% 
% subplot(2,2,4);
% margin(CLTF,opts)
% grid


