/*
 * local_var_longmax_28388D_cpu01.h
 *
 *  Created on: Feb 27, 2020
 *      Author: weizhong
 */

#ifndef LOCAL_VAR_LONGMAX_28379D_CPU01_H_
#define LOCAL_VAR_LONGMAX_28379D_CPU01_H_

extern volatile struct DAC_REGS* DAC_PTR[4];
extern volatile struct EPWM_REGS* ePWM[13];
extern volatile struct SPI_REGS* SPIs[3];
typedef     unsigned char   uint8_t;                            // 1 byte 0 to 255
//###############################################################################
// Put measurements in the shared memory for CPU 2
Uint32 max_value = 0;

float           running_time     = 0.0;                                 // elapsed time

#pragma DATA_SECTION(sData_32,"SHARERAMGS0");                      // sending data to CPU2
#pragma DATA_SECTION(tData,"SHARERAMGS1");                           // received data from CPU2 need to assign the ownership to CPU2
//..............................Defines...........................................
/* SPI */

#define             SLAVE                 0                               // SPI slave master mode - slave
#define             MASTER                1                               // SPI master mode
#define             DIS_LOOPBACK          0                               // Disable SPI loopback
#define             EN_LOOPBACK           1                               // Enable SPI loopback
#define             SPI_CPOL              0                               // SPI clock polarity 0 when the clock idles
#define             SPI_CPHA              0                               // SPI clock phase, 0-capture data when rising, 1-capture data when falling
#define             WORD_BIT             16                              // SPI word length
//#define             oversample_factor     8                              //oversampling factor for averaging
//#define             Phase_num_DC          1                                // Paralleled DC phase number
//#define             i_Phase_num_DC       1/Phase_num_DC                    // reversed phase number of DC side


float              rData_32_local[ADC_trans_num];                      // define local copy of read data from CPU2

volatile Uint16 *DMADest;                                           // DMA destination
volatile Uint16 *DMASource;                                         // DMA source
uint16_t            sample_num = 0;                                 // sample index for SPI, update every SPI fetch


// ePWM Defines -----------------------------------------------------------------------------------
#define             EPWM_DBRED             20                  //  x TBCLKs for Deadband rising edge delay was 150
#define             EPWM_DBFED             20                  //  x TBCLKs for Deadband Falling edge delay was 150
#define             EPWM_A                  1                    //  Phase A PWM channel define
#define             EPWM_B                  2                    //  Phase B PWM channel define
#define             EPWM_C                  3                    //  Phase C PWM channel define
#define             EPWM_D                  4                    //  Phase D PWM channel define
#define             EPWM_E                  5                    //  Phase E PWM channel define
#define             EPWM_F                  6                    //  Phase F PWM channel define
//#define             EPWM_fan_grid           11                    //  Phase A fan PWM channel define
//#define             EPWM_fan_batt           12                    //  Phase B fan PWM channel define
#define             EPWM_fan_a_b            7                    //  Phase A and B fan PWM channel define
#define             EPWM_fan_c_d            8                    //  Phase C and D fan PWM channel define
#define             EPWM_fan_e_f            11                    //  Phase E and F fan PWM channel define
#define             EPWM_adc_interrupt      9
#define             EPWM_control_interrupt 10
//#define             EPWM_fan_C              12                    //  Phase C fan PWM channel define
//#define             EPWM_fan_D              12                   //  Phase D fan PWM channel define
//#define             EPWM_fan_E              8                   //  Phase E fan PWM channel define
//#define             EPWM_fan_F              8                   //  Phase F fan PWM channel define
//Uint32              EPwm7TimerIntCount;
//Uint32              EPwm8TimerIntCount;
uint16_t            TempPIEIER;                                     // this is so epwm9 interrupt can interrupt epwm10 interrupt

//...........................................Adjustable variables......................
int                 frq                        = 20;//20;                         // Switching freq (KHz)
int                 frq_fan                    = 25;                             // Fan freq (KHz) should be 25
int                 frq_ADC                    = 80;               // ADC frequency
int                 frq_control                = 20;//20;                // control interrupt frequency
#define             EPWM_PRD7                   (200000.0/frq)/4.0   // switching period             // Counter input for ePWM based on frq (divided by 2 when pwm is configured to count up and down)
#define             EPWM_PRD_ADC                (200000.0/frq_ADC)/2.0 // ADC period
#define             EPWM_PRD_fan                (200000.0/frq_fan)/4.0  // fan PWM period
#define             EPWM_PRD_control            (200000.0/frq_control)/2.0 // control period

const int   oversample_factor = 4;
float oversample_factor_math  = 0.0; //for math with oversample calculations
float oversample_period       = 0.0; //multiplication instead of division for calculations
//float i_oversample_factor = 1/oversample_factor;
int   oversample_counter = 0;
int   oversample_remove = 0;
int   control_counter = 1;
int   sample_counter = 1;

float VphaseA_oversample_buffer[oversample_factor];
float VphaseB_oversample_buffer[oversample_factor];
float VphaseC_oversample_buffer[oversample_factor];
float VphaseD_oversample_buffer[oversample_factor];
float VphaseE_oversample_buffer[oversample_factor];
float VphaseF_oversample_buffer[oversample_factor];

float IindA_oversample_buffer[oversample_factor];
float IindB_oversample_buffer[oversample_factor];
float IindC_oversample_buffer[oversample_factor];
float IindD_oversample_buffer[oversample_factor];
float IindE_oversample_buffer[oversample_factor];
float IindF_oversample_buffer[oversample_factor];

float IgridA_oversample_buffer[oversample_factor];
float IgridB_oversample_buffer[oversample_factor];
float IgridC_oversample_buffer[oversample_factor];
float IgridD_oversample_buffer[oversample_factor];
float IgridE_oversample_buffer[oversample_factor];
float IgridF_oversample_buffer[oversample_factor];

float Vbus_oversample_buffer[oversample_factor];

// status flags and toggles and counters ------------------------------------------------------------
int                 EN_AC_controller           = 0;
int                 EN_AC_controller_old       = 0;
int                 EN_DC_controller           = 0;
int                 EN_DC_controller_old       = 0;
int                 EN_fans                    = 1;                             // Enable fans
int                 EN_fans_old                = 0;
int                 EN_precharge               = 0;

int                 protection_on              = 0;
int                 protection_AC_volt         = 0;
int                 protection_AC_curr         = 0;
int                 protection_DC              = 0;
int                 RST_gate_driver            = 0;

int                 relay_precharge            = 0;                   // relay close toggle, 0-open, 1-close
int                 relay_batt                 = 0;                   // relay close toggle, 0-open, 1-close
int                 relay_grid                 = 0;                   // relay close toggle, 0-open, 1-close

int                 precharge_counter1         = 0;
int                 precharge_counter2         = 0;
int                 count_RST                  = 0;
int                 i                          = 0;

int                 StopA                      = 0;                            // Manual trip zone for phase A
int                 StopB                      = 0;                            // Manual trip zone for phase B
int                 StopC                      = 0;                            // Manual trip zone for phase C
int                 StopD                      = 0;                            // Manual trip zone for phase A
int                 StopE                      = 0;                            // Manual trip zone for phase B
int                 StopF                      = 0;                            // Manual trip zone for phase C

int                 Phase_num_DC               = 1;                            // Paralleled DC phase number

// startup counters and flags ------------------------------------------------------------
int                 EN_startup                 = 0;                            // Enable the startup process
unsigned long int   precharge_counter          = 0;
int                 Flag_precharge             = 0;
int                 Flag_inrush                = 0;
unsigned long int   Vgrid_counter              = 0;
unsigned long int   PLL_counter1               = 0;
unsigned long int   PLL_counter2               = 0;
unsigned long int   DCbus_counter              = 0;
int                 EN_voltageCTRL_counter     = 0;
int                 InrushCurrentCounter       = 0;
float               Vdc_precharge              = 120.0;
float               Vmgrid_rated               = 42.43;

unsigned long int precharge_counter_complete   = 20000;
unsigned long int gridvoltage_check            = 20000;
unsigned long int PLLcheck1                    = 20000;
unsigned long int PLLcheck2                    = 20000;
unsigned long int DCbusControl_check           = 20000;
//unsigned long int precharge_DCbus_resistive_min 0.7*2*Vmgrid_rated
//unsigned long int precharge_DCbus_resistive_max 1.3*2*Vmgrid_rated

// initial duty cycles and gpio reads --------------------------------------------------------------
bool                DESAT_read[12]             = {0,0,0,0,0,0,0,0,0,0,0,0};     // DESAT pin status
bool                RDY_read[12]               = {0,0,0,0,0,0,0,0,0,0,0,0};     // DESAT pin status
float               duty_phase[6]              = {0.5,0.5,0.5,0.5,0.5,0.5};
float               duty_manual                = 0.5;
//float               duty_fan_grid              = .2;
//float               duty_fan_batt              = .8;  //this is 1-D
//float               duty_fan                   = .5;
float               duty_fan[6]                = {0.5,0.5,0.5,0.5,0.5,0.5};
float               max_temp_grid              = 0;    //gridside heatsink temperature
float               max_temp_batt              = 0;    //battery side heatsink temperature

// ........................ADC defines .....................
const int             adc_resolution =      ADC_RESOLUTION_12BIT;
const int             adc_signalmode =      ADC_SIGNALMODE_SINGLE;
const int             acq_window     =      14;//14;                              // ADC window was 14
const int             adc_prescale   =      6;                               // Acquisition window acq_window*5ns (1/200MHz) was 6
#define             ADC_RESOLUTION  ADC_RESOLUTION_12BIT
#define             ADC_SIGNALMODE  ADC_SIGNALMODE_SINGLE
const int           ADC_PRESCALE    = 6;                            // ADC clock scale, was 6

// sensor ADC readings and calibrations -----------------------------------------------------------
float Igrid_meas[6]  = {0.0,0.0,0.0,0.0,0.0,0.0};
float Vbus_meas      = 0.0;
float Iind_meas[6]   = {0.0,0.0,0.0,0.0,0.0,0.0};
float Vphase_meas[6]   = {0.0,0.0,0.0,0.0,0.0,0.0};

float Temp_meas[6]   = {0.0,0.0,0.0,0.0,0.0,0.0};
int   temp_meas_counter = 0;

float Vphase_meas_offset[6] = {2.1919,-0.2956,0.5954,0.4053,-1.2739,0.4425};//{1.3842,-0.7066,0.5954,0.4053,0.4053,0.4053};//{0.8443,-1.3072,0.3429,0.4053,1.2902,0.4053};//{-16.782,-16.782,-0.0802,-0.4118,-0.0802,0.2653};//{-3.2418,-5.4019,-2.7374,-0.5706,-1.8038,0.622};//
float Iind_meas_offset[6] = {122.69,124.6,125.01,125.308,126.308,127.208}; //{127.25,126.9,126.05,125.308,126.308,127.208}; //{124.25,124.25,124.25,124.25,124.25,124.25}; //{124.369,125.192,124.863,124.808,124.808,124.808}; //{2348,2372,2353,2425,2329,2336};
float Igrid_meas_offset[6] = {127.25,126.9,126.05,125.308,126.308,127.208}; //{124.13,123.74,123.74,126.5326,126.5326,126.5326}; //{2308,2344,2348,2355,2337,2240};
float Vbus_meas_offset = 0.9407;

float cal_vphase[6] = {0.2816,0.2839,0.2809,0.2738,0.2809,0.2752};//{0.2806,0.2826,0.2779,0.2738,0.2738,0.2738};//{0.2789,0.2857,0.2826,0.2738,0.2787,0.2738};//{0.3496,0.3496,0.2927,0.2946,0.2927,0.2872};//{0.3385,0.3406,0.2807,0.2846,0.2833,0.2773};//phase voltage sensor linear calibration
float cal_vphase_2nd[6] = {-0.00001949, -0.00001849, -0.00001626, -0.0000201, -0.0000201, -0.0000201};//phase voltage sensor polynomial calibration second order coefficient
float cal_vphase_1st[6] = {0.2842, 0.27975, 0.27057, 0.3131, 0.3131, 0.3131};//phase voltage sensor polynomial calibration first order coefficient
float cal_vphase_0th[6] = {-23.107, -19.97, -22.0063, 0.0, 0.0, 0.0};//phase voltage sensor polynomial calibration zeroth order coefficient
float cal_Igrid[6] = {0.0669, 0.0556, 0.0556, 0.053775, 0.053775, 0.053775}; //grid current sensor calibration
float cal_Iind[6] = {0.0544, 0.0554, 0.0555, 0.056, 0.056, 0.056};//{0.0566, 0.0564, 0.0560, 0.056, 0.056, 0.056};//{0.0572, 0.0572, 0.0572, 0.0572, 0.0572, 0.0572}; // inductor current sensor calibration
float cal_Vbus = 0.2853323; //0.3263 dc bus voltage sensor calibration
float cal_Vbus_2nd = -0.000025339;//0.0000201346;//DC bus voltage sensor polynomial calibration second order coefficient
float cal_Vbus_1st = 0.30931;//0.31311;//DC bus voltage sensor polynomial calibration first order coefficient
float cal_Vbus_0th = 3.53069;//0.0;//DC bus voltage sensor polynomial calibration first order coefficient

unsigned long int Vphase_oversample_running_total[6] = {0,0,0,0,0,0}; //{A,B,C,D,E,F}
unsigned long int Iind_oversample_running_total[6] = {0,0,0,0,0,0}; //{A,B,C,D,E,F}
unsigned long int Igrid_oversample_running_total[6] = {0,0,0,0,0,0}; //{A,B,C,D,E,F}
unsigned long int Vbus_oversample_running_total = 0;

float Vphase_meas_uncal[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Igrid_meas_uncal[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Iind_meas_uncal[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Vbus_meas_uncal = 0;

float Vphase_meas_cal[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Iind_meas_cal[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Igrid_meas_cal[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Vbus_meas_cal = 0;

float DESAT_error[13]     = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; // saving DESAT data [VA, VB, VC, VD, VE, VF, IA, IB, IC, ID, IE, IF, Vbus]

//..................variables for averaging in control.................//
int oversample_factor_inCTRL = 8;
//float i_oversample_factor = 1/oversample_factor;
int oversample_counter_inCTRL = 0;
//int control_counter = 1;
//int sample_counter = 1;

float Vphase_oversample_running_total_inCTRL[6] = {0.0,0.0,0.0,0.0,0.0,0.0}; //{A,B,C,D,E,F}
float Iind_oversample_running_total_inCTRL[6] = {0.0,0.0,0.0,0.0,0.0,0.0}; //{A,B,C,D,E,F}
float Igrid_oversample_running_total_inCTRL[6] = {0.0,0.0,0.0,0.0,0.0,0.0}; //{A,B,C,D,E,F}
float Vbus_oversample_running_total_inCTRL = 0;

float Vphase_meas_uncal_inCTRL[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Igrid_meas_uncal_inCTRL[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Iind_meas_uncal_inCTRL[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
float Vbus_meas_uncal_inCTRL = 0;

//..................variables for moving average....................//
//float Vbatt_meas[6]     = {0.0,0.0,0.0,0.0,0.0,0.0};                            // Define measured battery voltage 0,1,2 - A,B,C,D,E,F
int   buffer_index   = 0;                               // Moving average buffer indicator, when = MA_buffer_sz,averaging starts
const int   MA_buffer_sz = 8;                           // MA window size.  was 20
/*
float Vbatt_meas_avg = 0.0;
float Vbatt_MA_sum   = 0.0;                             // MA sum

float Vout_meas_avg[6] = {0.0,0.0,0.0,0.0,0.0,0.0}; //{A,B,C,D,E,F}
float Vout_MA_sum[6] = {0.0,0.0,0.0,0.0,0.0,0.0}; //{A,B,C,D,E,F}
float Vout_buffered_A[2];
float Vout_buffered_B[2];
float Vout_buffered_C[2];
float Vout_buffered_D[2];
float Vout_buffered_E[2];
float Vout_buffered_F[2];

float Iout_meas_avg[6] = {0.0,0.0,0.0,0.0,0.0,0.0}; //{A,B,C,D,E,F}
float Iout_MA_sum[6] = {0.0,0.0,0.0,0.0,0.0,0.0}; //{A,B,C,D,E,F}
float Iout_buffered_A[2];
float Iout_buffered_B[2];
float Iout_buffered_C[2];
float Iout_buffered_D[2];
float Iout_buffered_E[2];
float Iout_buffered_F[2];

float Iind_meas_avg[6] = {0.0,0.0,0.0,0.0,0.0,0.0}; //{A,B,C,D,E,F}
float Iind_MA_sum[6]   = {0.0,0.0,0.0,0.0,0.0,0.0};                             // MA sum
float Iind_buffered_A[2];
float Iind_buffered_B[2];
float Iind_buffered_C[2];
float Iind_buffered_D[2];
float Iind_buffered_E[2];
float Iind_buffered_F[2];
*/
float Vbus_meas_avg = 0;
float Vbus_MA_sum = 0;
float Vbus_buffered[8];

// old variables ---------------------------------------------------------------------------------------------

//int                 EN_CV                      = 1;                            // CV controller EN_controllerable
//int                 EN_duty_manual             = 0;                            // Manual duty cycle overwrite

//int                 EN_SPICtr                  = 0;                             // enable high-level controller to control start/stop...
//float               Ibatt_ref_const            = 3;                            // current reference if CV controller is disabled (divided by 3 for each phase)


//float               fan_init_duty              = 0.5;                   //  initial duty cycle for fans
//float               IDC_adj                    = 1.0;                          // DC bus stabilization currEN_controllert that charges/discharges the DC bus capacitor
//const float         Vbus_lower                 = 650;                          // lower voltage boundary to EN_controllergage the DC bus stabilization
//const float         Vbus_upper                 = 700;                          // upper voltage boundary to EN_controllergage the DC bus stabilization
//#define             Tsample                     0.5/(frq*1000.0)               // Sampling period (second) half of switching period
//float               Tsample                     = 0.0;
//float               clcdiv                      = 4.0;                          // High speed clock division, used for generating 1kHz PWM otherwise the minimum is 3kHz (modify the HSCLKDIV to 2 for /4)

//float           V1_meas_avg      = 0.0;
//float           V2_meas_avg      = 0.0;
//float           I1_meas_avg      = 0.0;
//float           I2_meas_avg      = 0.0;
//float           V_LV_meas_avg    = 0.0;
//float           I_LV_meas_avg    = 0.0;
//float           IDC_meas_avg     = 0.0;
//unsigned int        EOC_done = 0;                                   // Define a flag showing EN_controllerd of conversion for two ADCs
//unsigned int theta_flag = 0;                                      // Define a flag showing feedforward theta has beEN_controller set
//unsigned int xint5_count = 0;                                     // Counter for Xbar5 interrupt

//#define             phase_shift_B               EPMW_PRD7 * 0.333 * 2             // define the phase multiply by 2 due to updown counter
//#define             phase_shift_C               EPMW_PRD7 * 0.666 * 2            // define the phase
//float               pilot_duty                  = 0.954;                        // Pilot duty cycle for current limit, d = I/2.5 + 64 (51<I<80), = I/0.6 (6<I<51)
//Uint16                 prd                        = 0;                                                        // Varying the counter on the go

//........ Safety code .......//
//float               OCallow             = 30;                            // how many time the over currEN_controllert evEN_controllert can happEN_controller, don't shut off until meet condition
//int                 Count_ADCint        = 0;                            // Tracking the ADC event
//int                 OCconsec            = 0;                            // Tracking consecutive OC evEN_controllert
//unsigned int        I_over              = 40;                            // OvercurrEN_controllert protection
//unsigned int        Vbatt_over          = 500;                           // Overvoltage protection
//unsigned int        Vbatt_low           = 280;                           // minimum battery voltage (trigger protection when EN_controller == 1)
//unsigned int        Vbus_over_high        = 850;                          // bus overvoltage protection
//unsigned int        Vbus_over_low        = 750;                          // bus overvoltage protection
//unsigned int        Vbus_over_high_oneshot        = 900;                          // bus overvoltage protection
//unsigned int        Vbus_over_low_oneshot        = 700;                          // bus overvoltage protection


//Matt's protection variables
//float                 I_over_batt         = 999999;//60;
//float                 I_over_grid         = 999999;//60;
//int                 V_over_batt         = 700;
//int                 V_over_grid         = 700;
//float                 I_over_batt_oneshot         = 999999;//90;
//float                 I_over_grid_oneshot         = 999999;//90;
//int                 V_over_batt_oneshot         = 900;
//int                 V_over_grid_oneshot         = 900;
//float               OC_OV_error[13]     = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; // saving overvoltage/overcurrent data [VA, VB, VC, VD, VE, VF, IA, IB, IC, ID, IE, IF, Vbus]

//int                 protection_triggernum=0;                            // allowable over-currEN_controllert evEN_controllert count
//int                 error_batt_oc[3]    = {0,0,0};                            // Battery over currEN_controllert protection indicator
//float               error_batt_oc_value[3] = {0.0,0.0,0.0};
//int                 error_batt_ov       = 0;                            // Battery over votlage protection indicator
//int                 error_batt_lv       = 0;                             // Bus low voltage protection indicator
//int                 error_bus_oc[3]     = {0,0,0};                            // Bus over currEN_controllert protection indicator
//float               error_bus_oc_value[3] = {0.0,0.0,0.0};
//int                 error_bus_ov        = 0;                             // Bus over voltage protection indicator




//float               Vbatt_ref           = 500;                      // Batter voltage referEN_controllerce, i.e. maximum allowable voltage for the battery pack
//float               Ibatt_ref_upper     = 4;                        // Default upper boundary of the battery currEN_controllert referEN_controllerce, i.e. charging limit, set to negative when discharging is needed
//float               Ibatt_ref_lower     = -5;                        // Lower boundary of the battery currEN_controllert  referEN_controllerce, i.e. the maximum discharging limit
//float               Ibatt_ref_CV        = 0.0;                      // initialize the output from the CV PI controller
//float               Ibatt_ref_CV_DCstab = 0.0;                      // initialize the output from the CV PI controller after DC bus stabilization
//float               duty_phase[6]        = {0.0,0.0,0.0,0.0,0.0,0.0};                      // PHASE A duty cycle for the upper switch for the buck converter default 0 -> disconnect load from source


//int                 relay_on_num       = 0;                        // record how many times the relay B triggered on
//float               duty_fwd            = 0.0;                      // Feed forwarded duty cycle value
//float               duty_min            = 0.05;                        // minimum duty cycle
//float               duty_max            = 0.95;                      // maximum duty cycle

//int                 EN_EVcomm           = 0;                        // EN_EVcomm function for ev communication pwm signals
//int                 EN_EVcomm_old       = 0;
                        // precharge toggle, 0-not active, 1-active
//int               precharge_time      = 1;                     // precharge time in us
//float               precharge_start     = 0;                        // start time variable for precharge
//.......................................... Values to export data .....................//
#define             sample_max          (600U)                      // the maximum number of samples
float               Export_data[2][sample_max];                     // initialize the  exported data matrix
unsigned int        capture             = 0;                        // start of the data saving: 0 - stop, 1 - start
unsigned int        sample              = 1;                        // the sample point index, 0 - sample_max-1

//float Ibatt_meas[3] = {0.0,0.0,0.0};
//Float Vbus_buffered[MA_buffer_sz];
//.......................Initialize error between measurements and reference...................
//float Vbatt_error           = 0.0;                            // The error betweEN_controller referEN_controllerce and measured battery voltage
//float Vbatt_error_I_k       = 0.0;                            // Accumulated error on battery voltage at currEN_controllert measuremEN_controllert
//float Vbatt_error_I_k_1     = 0.0;                            // Accumulated error on battery voltage at previous measuremEN_controllert
//float Ibatt_error[3]        ={0.0,0.0,0.0};                            // The error betweEN_controller referEN_controllerce and measured battery currEN_controllert
//float Ibatt_error_I_k[3]    ={0.0,0.0,0.0};                            // Accumulated error on battery currEN_controllert at currEN_controllert measuremEN_controllert
//float Ibatt_error_I_k_1[3]  ={0.0,0.0,0.0};                            // Accumulated error on battery currEN_controllert at previous measuremEN_controllert
//float Iind_error[3]         ={0.0,0.0,0.0};
//float Iind_error_I_k[3]     ={0.0,0.0,0.0};
//float Iind_error_I_k_1[3]   ={0.0,0.0,0.0};
//float Vbatt_fake            = 200.0;                          // The fake battery voltage for feed forward, it will be set to the first measurement of the battery voltage when the controller is enabled
//float Vbus_fake             = 400.0;
//.......................ADC compensation and conversion values (Interface card V2)(Inverter board + 28379D Dec. 05,2019)..............
//float G_iv_A            = 40.3877;               // CurrEN_controllert sEN_controllersor gain: V/A (24.5mV/A)
//float G_iv_B            = 40.3225;
//float G_iv_C            = 40.45307;
//float G_vdc             = 444.266738;              // ADC reading -> Vdc
//float comp_RA           = 0.99228;               // phase A ADC voltage divider compensation (not 1.5V precisely)
//float comp_RB           = 0.9942;               // phase B ADC voltage divider compensation (not 1.5V precisely)
//float comp_RC           = 0.99212;                // phase C ADC voltage divider compensation (not 1.5V precisely)
//float convADC           = 3.0/4096.0;           // ADC Vref divided by ADC precision (2^12)
//float iconvADC          = 4096.0/3.0;           // ADC precision divided by ADC Vref
//float correctionVdc     = 0;//0.00319545;             // Vdc ADC compensation
//float G_vdiv            = (32.37+99.7)/32.37;   // Voltage divider gain for quick test
//float Ia_comp           = 0;                  // Compensation for phase A inverter current measurement, constant offset observed
//float Ib_comp           = 0;                  // Compensation for phase B inverter current measurement, constant offset observed
//float Ic_comp           = 0;                  // Compensation for phase B inverter current measurement, constant offset observed



//.......................ADC compensation and conversion values (Interface card V2)(Component board)


/* Output voltage sensor */
// without connecting the op amp on the component board
//float G_Vbatt                   = 397.3615195;              // voltage gain
//float correctionVbatt           = 0.0022841;                // zero voltage compensation (V)
//.......................Gains for PI controller (1 - Constant voltage, 2 - constant current)...............
//20k switching
//const float Kp1             = 0.005;
////const float Kp2             = 0.0001;                     // simulation kp
////const float Kp2             = 1e-8;
//const float Kp2             = 0.001;
//const float Ki1             = 10.0;
////const float Ki2             = 0.2;
//const float Ki2             = 0.0045;

/* 10k switching

const float Kp1             = 0.001;
const float Kp2             = 0.002;
const float Ki1             = 10.0;
const float Ki2             = 0.01;
*/
/* 40k switching*/
//float Kp1             = 1e-5;    // 1 is voltage 2 is current
//float Kp2             = 0.00005;    // 0.001 for 16 kHz
//float Ki1             = 0.5;     //
//float Ki2             = 0.1;

// better response for both AC/DC and DC/DC
//float Kp1             = 1e-3;    // 1 is voltage 2 is current
//float Kp2             = 3e-3;    // original 1e-4;    // 0.001 for 16 kHz
//float Ki1             = 1;     //
//float Ki2             = 0.01;

//float Vbus_meas_avg = 0;
//float Vbus_MA_sum = 0;

//float Vbus_meas_ADC = 0;
//float testcal1 = 1;
//float testcal2 = 1;

int test_var = 0;


//....................................DC/DC side control variables...................................//

//...........................................Adjustable variables......................
int                 EN_CV                      = 0;                            // CV controller EN_controllerable
int                 EN_duty_manual             = 0;                            // Manual duty cycle overwrite
int                 EN_protection              = 1;                             // Enable protection
float               Ibatt_ref_const            = 2;                            // current reference if CV controller is disabled (divided by 3 for each phase)
//float               frq                        = 50.0;                         // Switching freq (KHz)
int                 frq_EVcomm                 = 1;                             // EV comm freq (KHz)
//float               IDC_adj                    = 1.0;                          // DC bus stabilization currEN_controllert that charges/discharges the DC bus capacitor
//const float         Vbus_lower                 = 650;                          // lower voltage boundary to EN_controllergage the DC bus stabilization
//const float         Vbus_upper                 = 700;                          // upper voltage boundary to EN_controllergage the DC bus stabilization
//#define             Tsample                     0.5/(frq*1000.0)               // Sampling period (second) half of switching period
//float               Tsample                     = 0.0;
//float               clcdiv                      = 4.0;                          // High speed clock division, used for generating 1kHz PWM otherwise the minimum is 3kHz (modify the HSCLKDIV to 2 for /4)
//#define             EPMW_PRD7                   (200000.0/frq)/2.0             // Counter input for ePWM based on frq (divided by 2 whEN_controller pwm is configured to count up and down)
//#define             EPMW_PRD_EVcomm             (200000.0/frq_EVcomm)/(2.0*clcdiv)      // Counter input for ePWM based on frq (divided by 2 whEN_controller pwm is configured to count up and down)
//float               pilot_duty                  = 0.954;                        // Pilot duty cycle for current limit, d = I/2.5 + 64 (51<I<80), = I/0.6 (6<I<51)
//Uint16                 prd                        = 0;                                                        // Varying the counter on the go
//int                 StopA                       = 0;                            // Manual trip zone for phase A
//int                 StopB                       = 0;                            // Manual trip zone for phase B
//int                 StopC                       = 0;                            // Manual trip zone for phase C

//........ Safety code .......//
float               OCallow             = 8;                            // how many time the over currEN_controllert evEN_controllert can happEN_controller, don't shut off until meet condition
int                 Count_ADCint        = 0;                            // Tracking the ADC event
int                 OCconsec            = 0;                            // Tracking consecutive OC evEN_controllert
unsigned int        I_over              = 60;                            // OvercurrEN_controllert protection
unsigned int        Vbatt_over          = 500;                           // Overvoltage protection
unsigned int        Vbus_over_hi        = 1000;                          // bus overvoltage protection
unsigned int        Vbus_over_lo        = 750;                          // bus overvoltage protection
//int                 protection_on       = 0;                            // Tripzone indicator 1-on, 0-off
int                 protection_triggernum=0;                            // allowable over-currEN_controllert evEN_controllert count
int                 error_batt_oc[3]    = {0,0,0};                            // Battery over currEN_controllert protection indicator
float               error_batt_oc_value[3] = {0.0,0.0,0.0};
int                 error_batt_ov       = 0;                            // Battery over votlage protection indicator
int                 error_batt_lv       = 0;                             // Bus low voltage protection indicator
int                 error_bus_oc[3]     = {0,0,0};                            // Bus over currEN_controllert protection indicator
float               error_bus_oc_value[3] = {0.0,0.0,0.0};
int                 error_bus_ov        = 0;                             // Bus over voltage protection indicator

unsigned int        relay               = 0;                            // relay close toggle, 0-open, 1-close

float               Vbatt_ref           = 5;                      // Batter voltage referEN_controllerce, i.e. maximum allowable voltage for the battery pack
float               Ibatt_ref_upper     = 8;                        // Default upper boundary of the battery currEN_controllert referEN_controllerce, i.e. charging limit, set to negative when discharging is needed
float               Ibatt_ref_lower     = -5;                        // Lower boundary of the battery currEN_controllert  referEN_controllerce, i.e. the maximum discharging limit
float               Ibatt_ref_CV        = 0.0;                      // initialize the output from the CV PI controller
float               Ibatt_ref_CV_DCstab = 0.0;                      // initialize the output from the CV PI controller after DC bus stabilization
//float               duty_phase[3]        = {0.0,0.0,0.0};                      // PHASE A duty cycle for the upper switch for the buck converter default 0 -> disconnect load from source
//float               duty_phaseB          = 0.0;                      // PHASE B duty cycle for the upper switch for the buck converter default 0 -> disconnect load from source
//float               duty_phaseC          = 0.0;                      // PHASE A duty cycle for the upper switch for the buck converter default 0 -> disconnect load from source

//float               relayA_on           = 0.0;
//float               relayB_on           = 0.0;                        //
//float               relayC_on           = 0.0;                        //
int                 relay_on_num       = 0;                        // record how many times the relay B triggered on
float               duty_fwd            = 0.0;                      // Feed forwarded duty cycle value
float               duty_min            = 0.05;                        // minimum duty cycle
float               duty_max            = 0.95;                      // maximum duty cycle
//int                 EN_controller       = 0;                        // EN_controllerable function for PWM, set to 1 in debugging mode whEN_controller ready to run
int                 EN_EVcomm           = 0;                        // EN_EVcomm function for ev communication pwm signals
int                 EN_EVcomm_old       = 0;
//int                 EN_controller_old          = 0;

//#####################################################################################

//........................Globals..................................

/* EPWM */
Uint32              EPwm7TimerIntCount;
Uint32              EPwm8TimerIntCount;
unsigned int        EOC_done = 0;                                   // Define a flag showing EN_controllerd of conversion for two ADCs
//unsigned int theta_flag = 0;                                      // Define a flag showing feedforward theta has beEN_controller set
//unsigned int xint5_count = 0;                                     // Counter for Xbar5 interrupt

// ........................ADC defines .....................
//const int             adc_resolution =      ADC_RESOLUTION_12BIT;
//const int             adc_signalmode =      ADC_SIGNALMODE_SINGLE;
//const int             acq_window     =      14;                              // ADC clock scale
//const int             adc_prescale   =      6;                               // Acquisition window acq_window*5ns (1/200MHz)

//.......................Initialize measuremEN_controllerts...................
float Vbatt_meas     = 0.0;                            // Define measured battery voltage 0,1,2 - A,B,C
float Ibatt_meas[3]  ={0.0,0.0,0.0};                            // Define measured avg currEN_controllert flowing to the battery ** inductor currEN_controllert right now due to the position of the sEN_controllersor is placed right after the cEN_controllerter tap**
//float Vbus_meas      = 0.0;                            // Define measured DC bus voltage
float Vbus_const     = 0.0;                            // Define manually adjusted bus voltage
float Ibus_meas[3]   ={0.0,0.0,0.0};                            // Define measured currEN_controllert from the AC side
float Ibus_meas_ex[3]={0.0,0.0,0.0};
float Vbatt_meas_ex  = 0.0;


//.......................Initialize error betweEN_controller measuremEN_controllerts and referEN_controllerce...................
float Vbatt_error           = 0.0;                            // The error betweEN_controller referEN_controllerce and measured battery voltage
float Vbatt_error_I_k       = 0.0;                            // Accumulated error on battery voltage at currEN_controllert measuremEN_controllert
float Vbatt_error_I_k_1     = 0.0;                            // Accumulated error on battery voltage at previous measuremEN_controllert
float Ibatt_error[3]        ={0.0,0.0,0.0};                            // The error betweEN_controller referEN_controllerce and measured battery currEN_controllert
float Ibatt_error_I_k[3]    ={0.0,0.0,0.0};                            // Accumulated error on battery currEN_controllert at currEN_controllert measuremEN_controllert
float Ibatt_error_I_k_1[3]  ={0.0,0.0,0.0};                            // Accumulated error on battery currEN_controllert at previous measuremEN_controllert
float Ibus_error[3]         ={0.0,0.0,0.0};
float Ibus_error_I_k[3]     ={0.0,0.0,0.0};
float Ibus_error_I_k_1[3]   ={0.0,0.0,0.0};
float Vbatt_fake            = 200.0;                          // The fake battery voltage for feed forward, it will be set to the first measurement of the battery voltage when the controller is enabled
float Vbus_fake             = 400.0;

//.....................DC/DC side control gains..................//
float Kp1             = 1e-5;    // 1 is voltage 2 is current
float Kp2             = 0.1;    // 0.001 for 16 kHz
float Ki1             = 0.5;     //
float Ki2             = 10;


#endif /* LOCAL_VAR_LONGMAX_28379D_CPU01_H_ */
