SimSetup = 1;

switch(SimSetup)
      case 0
         tsim = 3; % Simulated 1 second
         SysConfig = 1; % Use fully switched buck converter with digital controls
      case 1
         tsim = 4.5*3600; % Simulated 4.5 hours
         SysConfig = 2; % Use averaged model buck converter with continuous controls
end

V_in = 60; % DC input voltage

%% Battery Parameters
n_series = 10; % Number of series connected cells
n_parallel = 10; % Number of parallel branches
SOC_init = 0.5; % initial SOC

cell_cap = 6.5; % Cell capacitance
pack_cap = cell_cap * n_parallel; % Pack capacitance

cell_ConstI = 1.3; % Target constant charging current for each cell
cell_ConstV = 4.1; % Target constant charging voltage for each cell

ConstI = cell_ConstI * n_parallel; % Target constant charging current
ConstV = cell_ConstV * n_series; % Target constant charging voltage

MAX_SOC = 0.97; % State of charge when battery charging is stopped

%% Buck Parameters:
DCDC.L = 1.5e-3; % [H] - Output inductances
DCDC.Lr= 0.01; % [Ohm] - Inductor resistance
DCDC.C = 100e-6; % [C] - Output capacitance
DCDC.R = 25; % [Ohm] - Output resistance
DCDC.fs = 15000; % [Hz] - Switching frequency
DCDC.Ts = 1/DCDC.fs; % [s] - Switching period
DCDC.Vamp = V_in; % [V] - Peak voltage amplitude

%% Current Controls

% Small time constants
CC.PWM = 0.5*DCDC.Ts; % [s] - PWM modulator small time constant
CC.Tcs = 1/(2*pi*(10*DCDC.fs)); % [s] - Current sensor small time constant
CC.f_samp = DCDC.fs; % [Hz] - Sampling frequency
CC.Tsp = 1/CC.f_samp; % [s] - Sampling small time constant
CC.Tpe = CC.PWM + CC.Tcs + CC.Tsp; % [s] - Equivalent small time constant

% Dominant time constants
CC.Tn=2*DCDC.L/(2*DCDC.Lr);
CC.Ti=2*CC.Tpe;

% Controller
CC.Kp=CC.Tn/CC.Ti;
CC.Ki=1/CC.Ti;
CC.Tp_current=2*sqrt(CC.Ti*CC.Tpe);
CC.K_aw=1/CC.Kp;

CC.upper=DCDC.Vamp;
CC.lower=0;

%% Voltage controller
VC.Tp_Vloop = CC.Tsp*2; %CC.Tp_current/2;
VC.Tsp=VC.Tp_Vloop;
VC.Ti_Vloop = 8/DCDC.C*VC.Tp_Vloop*VC.Tp_Vloop;
VC.Tn_Vloop = 4*VC.Tp_Vloop;

VC.Kp = VC.Tn_Vloop/VC.Ti_Vloop;
VC.Ki = 1/VC.Ti_Vloop;
VC.K_aw=1/VC.Kp;
VC.upper=ConstI;
VC.lower=0;