//************************************************************************************************/
// @Module         FOC Position control
// @Filename       FOC_SPC_CTRL.H
// @Controller     XC16x Series
//
//
// @Description    This file contains references for FOC POS control Functions
//
//************************************************************************************************/
#ifndef _SPC_CTRL_H_
#define _SPC_CTRL_H_

//*************************************************************************************************
// @Includes
//*************************************************************************************************

 //*************************************************************************************************
// @Defines
//*************************************************************************************************

struct pi_controller                                       // PI-controller parameter            
{                                                                                
int  kp;                                                   // Proportional constant          
int  ymax;                                                 // Maximal ouput limit    
int  ymin;                                                 // Minimal ouput limit    
long yn;                                                   // Integrator buffer
int  ki;                                                   // Kp * T0/Ti                    

};

struct control_input                                 
{                                                                                
    long reference;                                       
    long actual;                                          
};

struct integral                                 
{                                                                                
    long speed;                                            // Integrator buffer
    long position;                                         // Integrator buffer
};


//*************************************************************************************************
// @Macros
//*************************************************************************************************

// FOC Start
//*************************************************************************************************
#define CTRL_VAR_DECL()\
    extern BIT gb_motor_status;\
    extern BIT gb_ctrap;\
    extern BIT gb_off;\
    extern BIT gb_on;\
    extern BIT gb_overcurrent;\
    extern C_BDATA g_status_word; \
    extern int C_SDATA g_once;\
    extern int C_SDATA g_i_counter;\
    extern int C_SDATA g_iq_comp_ref;\
    extern int C_SDATA g_id_comp_ref;\
    extern int C_SDATA g_adc_off[2];\
    extern int C_SDATA g_mod_index;\
    extern int C_SDATA g_voltage_angle;\
    extern int C_SDATA g_counter0;\
    extern int C_SDATA g_ramp_cte;\
    extern int C_SDATA g_speed_ref_max;\
    extern int C_SDATA g_rotor_angle_calibration;\
    extern int C_SDATA g_phi_rotor;\
    extern int C_SDATA g_voltage_vector;\
    extern int C_SDATA g_counter_positioning;\
    extern int C_SDATA g_phase_current_ref;\
    extern int C_SDATA g_phi_rotor_mem;\
    extern int C_SDATA g_i_phase_s;\
    extern int C_SDATA g_i_phase_t;\
    extern int C_SDATA g_i_alpha;\
    extern int C_SDATA g_i_beta;\
    extern int C_SDATA g_id_comp;\
    extern int C_SDATA g_iq_comp;\
    extern int C_SDATA g_f_d_comp;\
    extern int C_SDATA g_f_q_comp;\
    extern int C_SDATA g_phi_control;\
    extern int C_SDATA g_encoder_mem;\
    extern int C_SDATA g_test_position_k;\
    extern int C_SDATA g_test_speed_kp;\
    extern int C_SDATA g_test_speed_ki;\
    extern int C_SDATA g_test_speed_ymax;\
    extern int C_SDATA g_test_speed_ymin;\
    extern int C_SDATA g_test_current_kp;\
    extern int C_SDATA g_test_current_ki;\
    extern int C_SDATA g_test_current_ymax;\
    extern int C_SDATA g_test_current_ymin;\
    extern int C_SDATA g_trap_reset;\
    extern int C_SDATA g_speed_ref;\
    extern int C_SDATA g_position_rel;\
    extern int C_SDATA g_position_rel_mem;\
    extern unsigned int C_SDATA g_adc_start;\
    extern unsigned int C_SDATA g_encoder_meass[];\
    extern unsigned int C_SDATA g_circ_index;\
    extern int C_SDATA g_speed_enc;\
    extern long C_SDATA g_position_ref_user;\
    extern long C_SDATA g_position_ref_0;\
    extern struct pi_controller C_SDATA g_pi_current_d;\
    extern struct pi_controller C_SDATA g_pi_current_q;\
    extern struct pi_controller C_SDATA g_pi_speed;\
    extern struct control_input C_SDATA g_position;\
    extern struct integral C_SDATA generator;                  

#define CTRL_FUNC_DECL()\
    extern void motor_start(void);\
    extern void motor_stop(void);\
    extern void speed_ref_ramp(void); \
    extern void angle_calibration(void);\
    extern void blink_led(void);\
    extern void modulator(int ampl, int phi);\
    extern int pi_con_pos_co(int *pi_parameter,int reference,int actual);\
    extern int clarke_trans_co(int I_phase_s, int I_phase_t , int *ia);\
    extern int park_trans_co(int e_a,int e_b,int phi,int *a_b);\
    extern int cart_polar_conv_co(int real,int imaginar,int *phase);\
    extern int P_controller_co(long *x,int Kp);\
    void modulator_co(int ampl, int phi);\
    extern long generator_co(long *x,long y);\
    extern int adc_offset(int);\
    extern int pi_controller64(long *pi_parameter,int reference,int actual);

//*************************************************************************************************

CTRL_VAR_DECL()
CTRL_FUNC_DECL()
#if DAVECG_CONTROL_PANEL_ENABLE
COMM_FUNC_DECL()
#endif

#if DAVECG_KEIL
void ADC_viConv(void);
#endif // (KEIL == 1)
#if DAVECG_TASKING
    interrupt (ADC_C_INT) _localbank(-1)_cached void ADC_viConv(void);
#endif
//*************************************************************************************************
#if DAVECG_KEIL

#define ADC_ERROR_BANK1_SIG()\
void ADC_viError(void) interrupt ADC_E=CACHED using _FAST_ABANK1_ \
{

#define ADC_ERROR_BANK2_SIG()\
void ADC_viError(void) interrupt ADC_E_INT using Reg_bank_ADC \
{

#endif // DAVECG_KEIL

#if DAVECG_TASKING

#define ADC_ERROR_BANK1_SIG()\
interrupt (ADC_E_INT) _localbank(-1)_cached void ADC_viError(void) \
{

#define ADC_ERROR_BANK2_SIG()\
interrupt (ADC_E_INT) using (Reg_bank_ADC) void ADC_viError(void) \
{

#endif // DAVECG_TASKING
//*************************************************************************************************
#define POSITION_EXP 4
#define POSITION_FACTOR  33554
#define CONDITION_OPERATOR >
#define DUTY_CYCLE_THRESHOLD PWPD

//*************************************************************************************************

INLINE void FOC_PARAM_INIT(void)
{
    g_phase_current_ref		=	MOTOR_CURRENT_REF;
    g_ramp_cte				=	RAMP_CTE;
    g_position_ref_user		=	MOTOR_POSITION_REF;
	gb_motor_status			=	CONTROL_PANEL_ENABLE;
	g_trap_reset			=	1;
}

INLINE void INIT_CCU6_VAR(void)
{
    CCU6_T12PR		=  PULSE_PERIOD;
    CCU6_T13PR		=  T13_PERIOD;
	CCU6_T12DTC		=  (CCU6_T12DTC & 0xFFC0) | DEAD_TIME;
	CCU6_PSLR		=  PASSIVE_STATE;
	CCU6_TCTR4		=  0x4040;      // load CCU6 timer control register 4
}

INLINE void INIT_PI_VAR(void)
{
    g_test_speed_kp    = INIT_SPEED_KP; 
    g_test_speed_ki    = INIT_SPEED_KI; 
    g_test_speed_ymax  = PIC_SPEED_YMAX; 
    g_test_speed_ymin  = PIC_SPEED_YMIN; 
    g_test_current_kp    = INIT_CURRENT_KP; 
    g_test_current_ki    = INIT_CURRENT_KI; 
    g_test_current_ymax  = PIC_CURRENT_YMAX; 
    g_test_current_ymin  = PIC_CURRENT_YMIN;
	g_test_position_k = INIT_KP_P;
}

INLINE void SET_PI_VAR(void) 
{
	g_pi_current_d.kp   = g_test_current_kp; 
	g_pi_current_d.ki   = g_test_current_ki; 
	g_pi_current_d.ymax = g_test_current_ymax; 
	g_pi_current_d.ymin = g_test_current_ymin; 
	g_pi_current_q.kp   = g_test_current_kp; 
	g_pi_current_q.ki   = g_test_current_ki; 
	g_pi_current_q.ymax = g_test_current_ymax; 
	g_pi_current_q.ymin = g_test_current_ymin; 
	g_pi_speed.kp   = g_test_speed_kp; 
	g_pi_speed.ki   = g_test_speed_ki; 
	g_pi_speed.ymax = g_test_speed_ymax; 
	g_pi_speed.ymin = g_test_speed_ymin;
}

INLINE void INIT_CTRL_VAR(void) 
{
    gb_motor_status = 1;
    g_once = 0x0; 
    g_status_word = 0x0002; 
    g_rotor_angle_calibration = 0x0001; 
    g_voltage_vector = 0x0; 
    g_phase_current_ref = 536; 
    g_ramp_cte = RAMP_CTE; 
    g_speed_ref_max = SPEED_REF_MAX; 
    g_test_position_k = PC_POSITION_K;
}

//*************************************************************************************************

INLINE void MOTOR_RAMP_GEN(void)
{
}

INLINE void TRAP_RESET(void) 
{
    if (g_trap_reset == 1) 
    { 
        g_trap_reset = 0x0000; 
        gb_ctrap = 0; 
    }
}

INLINE void BLINK_LED(void) 
{
    blink_led();
}

INLINE void SET_TRAP(void) 
{
    gb_ctrap = 1;
}


INLINE void SET_MONITOR_TRAP(void) 
{
    motor_stop(); 
    gb_motor_status = 1; 
    SET_TRAP();  
}

INLINE void MOTOR_STOP(void)
{ 
    motor_stop(); 
    g_position_ref_user = g_position.actual; 
    g_position_ref_0    = g_position.actual;
}

INLINE void MONITOR_MOTOR_CONTROL(void) 
{
    if (gb_ctrap) 
    { 
        gb_motor_status = 1; 
    } 
    else 
    { 
        if (gb_motor_status == 0) 
        { 
            motor_start(); 
        } 
        else 
        { 
            MOTOR_STOP(); 
        } 
    }
}
    
INLINE void OFFSET_ANGLE_CALIBRATION(void)
{
	angle_calibration();
}

//*************************************************************************************************

INLINE void SET_ADC_SRC_DST_PTR(void)
{
    SRCP7 = C_SOF(g_adc_start);
    DSTP7 = C_SOF(ADC_CTR0);
}


INLINE void SET_ADC_CTR2(void)
{
#if CPU_FREQUENCY <= 20
    ADC_CTR2 = 0x0000;
    ADC_CTR2IN = 0x0000;
#endif // CPU_FREQUENCY <= 20
}

INLINE void SET_ADC_FST_INT(void)
{
#if REG_BANK_ADC == 1
    SET_FINT_CTRL_REG(ADC_viConv, BNKSEL0)
#endif // REG_BANK_ADC == 1
}

//*************************************************************************************************
        
INLINE void ADC_INIT3_CBLOCK(void)
{
    SRCP7 = C_SOF(g_adc_start);
    DSTP7 = C_SOF(ADC_CTR0);

#if REG_BANK_ADC == 1
    SET_FINT_CTRL_REG(ADC_viConv, BNKSEL0)
#endif // REG_BANK_ADC == 1

#if CPU_FREQUENCY <= 20
    ADC_CTR2 = 0x0000;
    ADC_CTR2IN = 0x0000;
#endif // CPU_FREQUENCY <= 20
}

//*************************************************************************************************

INLINE void GPT1_TMR22_CBLOCK(void)
{
   	long l_pos_reference = 0;
  
//GPT1 Timer2 Speed calculation block	
	GPT12E_T2 += T2_PERIOD; 
	g_speed_enc  = (GPT12E_T3 - g_encoder_meass[g_circ_index]) << SHIFT_VAL; 
	g_encoder_meass[g_circ_index] = GPT12E_T3; 
	g_circ_index++; 
    g_circ_index &= CIRC_INDEX_VAL;

//GPT1 Timer22 Position reference calculation block
#if DAVECG_KEIL
  if(g_position_ref_user < g_position_ref_0) 
  { 
    g_position_ref_0 -= g_ramp_cte; 
    if(g_position_ref_user >= g_position_ref_0) 
    { 
      g_position_ref_0 = g_position_ref_user; 
    } 
  } 
  if(g_position_ref_user > g_position_ref_0) 
  { 
    g_position_ref_0 += g_ramp_cte; 
    if(g_position_ref_user <= g_position_ref_0) 
    { 
      g_position_ref_0 = g_position_ref_user; 
    } 
  } 
  g_position.reference = generator_co(&generator.speed, g_position_ref_0); 
  C_CoLOAD(g_position_ref_user); 
  C_CoSUB(g_position.reference); 
  C_CoABS(); 
  l_pos_reference = C_CoSTORE(); 
  if(l_pos_reference < 72) 
  { 
    g_position.reference = g_position_ref_user; 
  }
  C_CoMULsu((GPT12E_T3 - g_encoder_mem), POSITION_FACTOR); 
  g_position_rel = C_CoSTOREMAS() >> (14- POSITION_EXP); 
  g_position.actual += g_position_rel - g_position_rel_mem; 
  g_position_rel_mem = g_position_rel; \
  g_speed_ref = P_controller_co(&g_position.reference, g_test_position_k);

#elif DAVECG_TASKING

if(g_position_ref_user < g_position_ref_0) 
{ 
g_position_ref_0 -= g_ramp_cte; 
if(g_position_ref_user >= g_position_ref_0) 
{ 
g_position_ref_0 = g_position_ref_user; 
} 
} 
if(g_position_ref_user > g_position_ref_0) 
{ 
g_position_ref_0 += g_ramp_cte; 
if(g_position_ref_user <= g_position_ref_0) 
{ 
g_position_ref_0 = g_position_ref_user; 
} 
} 
g_position.reference = generator_co(&generator.speed, g_position_ref_0); 
_CoLOAD((g_position_ref_user));
_CoSUB((g_position.reference));
_CoABS();
l_pos_reference = _CoSTORE();
if(l_pos_reference < 72)
{
g_position.reference = g_position_ref_user;
}
  _CoMULsu(((GPT12E_T3 - g_encoder_mem)), POSITION_FACTOR);
  _CoSHR(14 - POSITION_EXP);
  g_position_rel = _CoSTOREMAL();
  g_position.actual += g_position_rel - g_position_rel_mem;
  g_position_rel_mem = g_position_rel;
  g_speed_ref = P_controller_co(&g_position.reference,g_test_position_k);

#endif

//GPT1 Timer22 speed control block
#if DAVECG_KEIL
  g_iq_comp_ref = pi_con_pos_co(&g_pi_speed.kp, g_speed_ref, g_speed_enc); 
  C_CoLOAD_0_1(0, g_iq_comp_ref); 
  C_CoMIN_0_1(0, CURRENT_MAX); 
  C_CoMAX_0_1(0, -CURRENT_MAX); 
  g_iq_comp_ref = C_CoSTOREMAS();

#elif DAVECG_TASKING
if((gb_off == 0) && (g_rotor_angle_calibration == 2))
{
g_iq_comp_ref = pi_con_pos_co(&g_pi_speed.kp,g_speed_ref,g_speed_enc);
Int_CoLimit(0,g_iq_comp_ref,-CURRENT_MAX,CURRENT_MAX);
g_iq_comp_ref = _CoSTOREMAS();
}
#endif

//Over Current Check
#if DAVECG_CURRENT_SENSE          
	if((gb_off == 0) && (g_rotor_angle_calibration == 2)) 
    { 
        if((g_iq_comp >= OVER_CURRENT_MAX)||((g_iq_comp <= -OVER_CURRENT_MAX))) 
        { 
            g_i_counter++; 
            if(g_i_counter == OVER_CURRENT_TIME) 
            { 
                motor_stop(); 
                gb_motor_status = 1; 
                gb_overcurrent = 1; 
            } 
        } 
        else 
        { 
            if(g_i_counter > 0) 
            { 
                g_i_counter--; 
            } 
        } 
    }

#endif // (CURRENT_SENSE == 1)  

#if DAVECG_CONTROL_PANEL_ENABLE
	trace();
#endif
}

//*************************************************************************************************
// ROTOR ANGLE CALCULATION

INLINE void ROTOR_ANGLE_CALCULATION(void)
{
    #if DAVECG_TASKING
      _CoMULsu((GPT12E_T3 - g_encoder_mem),ROTOR_ANGLE_FACTOR);
      _CoSHR(16 - ROTOR_ANGLE_EXP);
      g_phi_rotor = _CoSTOREMAL() - g_phi_rotor_mem;
    #elif DAVECG_KEIL
      _mac_(CoMULsu ,(GPT12E_T3 - g_encoder_mem),ROTOR_ANGLE_FACTOR);
      g_phi_rotor = (int)(_lmac_sat_() >> ( 16 - ROTOR_ANGLE_EXP)) - g_phi_rotor_mem;
    #endif
}

//*************************************************************************************************
//PHASE CURRENT 

INLINE void PHASE_CURRENT_READ(void)
{
      if(g_adc_start == 0xA692)
      {
        g_i_phase_t = g_adc_off[1] - (ADC_DAT2  & 0x0FFC);
        g_i_phase_s = g_adc_off[0] - (ADC_DAT   & 0x0FFC);
      }
      else
      {
        g_i_phase_s = g_adc_off[0] - (ADC_DAT2  & 0x0FFC);
        g_i_phase_t = g_adc_off[1] - (ADC_DAT   & 0x0FFC);
      }
}

//*************************************************************************************************

        INLINE void ROTOR_ANGLE_CALLIBRATION(void)
		{
			angle_calibration();
		}

//*************************************************************************************************
// 3 / 2 TRANSFORMATION
        INLINE void CLARKE_TRANSFORMATION(void)
		{
			g_i_beta  = clarke_trans_co(g_i_phase_s, g_i_phase_t ,&g_i_alpha);
		}

//*************************************************************************************************
// ROTOR ORIENTATION
        INLINE void PARK_TRANSFORMATION(void)
		{
			g_id_comp = park_trans_co(g_i_alpha,g_i_beta,g_phi_rotor,&g_iq_comp);   
		}

//*************************************************************************************************
// CURRENT CONTROL (D COMPONENT)
        INLINE void CURRENT_CONTROL_FLUX_COMPONENT(void)
		{
			g_f_d_comp  = pi_con_pos_co(&g_pi_current_d.kp,g_id_comp_ref,g_id_comp);      
		}

//*************************************************************************************************
// CURRENT CONTROL (Q COMPONENT)
        INLINE void CURRENT_CONTROL_TORQUE_COMPONENT(void)
		{
			g_f_q_comp  = pi_con_pos_co(&g_pi_current_q.kp,g_iq_comp_ref,g_iq_comp); 
		}

//*************************************************************************************************
// STATOR ORIENTATION
        INLINE void CARTESIAN_TO_POLAR_CONVERSION(void)
		{
			g_mod_index = cart_polar_conv_co(g_f_d_comp,g_f_q_comp,&g_phi_control);
		}

//*************************************************************************************************
// MODULATOR
        INLINE void MODULATOR_CO(void)
		{
			modulator_co(g_mod_index, g_voltage_angle);
			CCU6_TCTR4    = 0x0040; 
		}

//*************************************************************************************************

INLINE void TRACE(void)
{
#if DAVECG_CONTROL_PANEL_ENABLE
  trace();
#endif
}

//*************************************************************************************************
//CHANGE  ADC TRIGGER
        INLINE void CHANGE_ADC_TRIGGER(void)
		{
			  if(g_speed_ref > 0)
			  {
				if((CCU6_CC61SR < DUTY_CYCLE_THRESHOLD) && (CCU6_CC62SR > (PWPD / 2)))
				{
				  ADC_DAT2  = 0x2000;
				  g_adc_start = 0xA694;
				}
				if((CCU6_CC62SR < DUTY_CYCLE_THRESHOLD) && (CCU6_CC62SR < CCU6_CC61SR))
				{
				  ADC_DAT2  = 0x4000;
				  g_adc_start = 0xA692;
				}
			  }
			  else
			  {
				if((CCU6_CC62SR < DUTY_CYCLE_THRESHOLD) && (CCU6_CC61SR > (PWPD / 2)))
				{
				  ADC_DAT2  = 0x4000;
				  g_adc_start = 0xA692;
				}
				if((CCU6_CC61SR < DUTY_CYCLE_THRESHOLD) && (CCU6_CC61SR < CCU6_CC62SR))
				{
				  ADC_DAT2  = 0x2000;
				  g_adc_start = 0xA694;
				}
			  }
		}

//*************************************************************************************************
		
INLINE void ADC_ISSR(void)
{
	ROTOR_ANGLE_CALCULATION();
	PHASE_CURRENT_READ();
    if(g_rotor_angle_calibration == 1)
    {
    ROTOR_ANGLE_CALLIBRATION();
    }
    else
    {
    CLARKE_TRANSFORMATION();
    PARK_TRANSFORMATION();
    CURRENT_CONTROL_FLUX_COMPONENT();
    CURRENT_CONTROL_TORQUE_COMPONENT();
    CARTESIAN_TO_POLAR_CONVERSION();
    g_voltage_angle  = g_phi_control + g_phi_rotor;
    }
    MODULATOR_CO();
    CHANGE_ADC_TRIGGER();
}
//*************************************************************************************************
//FOC END
//*************************************************************************************************

#endif // _FPC_CTRL_H_


