//*****************************************************************************/
// @Module              FOC Speed Control with Field Weakening
// @Filename            SFC_CTRL.C
// @Controller          XC16x Series
//
//
// @Description   This file contains functions for Speed Control with Field 
//                              Weakening through FOC
//
//*****************************************************************************/

//****************************************************************************
// @Includes
//****************************************************************************
#include "MAIN.H"

//****************************************************************************/
// @Imported Global Variables
//****************************************************************************/


extern int C_SDATA g_alt_sel0_P1L;
extern int C_SDATA g_alt_sel0_P1L_del;


#if DAVECG_CONTROL_PANEL_ENABLE
extern BIT gb_motor_status;
extern C_BDATA g_trigger_status;
#else
C_UBDATA g_trigger_status;                       
C_SBIT gb_motor_status C_ATBIT(g_trigger_status, 5);
#endif

//****************************************************************************/
// @Local Function Prototypes
//****************************************************************************/

void motor_start(void);
void motor_stop(void);
void speed_ref_ramp(void);
void blink_led(void);

void angle_calibration(void);
void nv_ref_ramp_generation(void);


//****************************************************************************
// @Imported Function Prototypes
//****************************************************************************
int adc_offset(int);
extern void driver_enable(void);

//****************************************************************************
// @Global Variables
//****************************************************************************


int C_SDATA g_once;
C_BDATA g_status_word;
C_SBIT gb_on            C_ATBIT(g_status_word, 0);         // ON                           
C_SBIT gb_off           C_ATBIT(g_status_word, 1);         // OFF                           
C_SBIT gb_ctrap         C_ATBIT(g_status_word, 5);         // Ctrap detection
C_SBIT gb_overcurrent   C_ATBIT(g_status_word, 6);         // Overcurrent detection 
int C_SDATA g_i_counter;
int C_SDATA g_counter0;

int C_SDATA g_iq_comp_ref;
int C_SDATA g_id_comp_ref;

int C_SDATA g_adc_off[2];
int C_SDATA g_mod_index;
int C_SDATA g_voltage_angle;

int C_SDATA g_rotor_angle_calibration;
int C_SDATA g_phi_rotor;
int C_SDATA g_counter_positioning;
int C_SDATA g_phase_current_ref;

int C_SDATA g_i_phase_s;
int C_SDATA g_i_phase_t;
int C_SDATA g_i_alpha;
int C_SDATA g_i_beta;
int C_SDATA g_id_comp;
int C_SDATA g_iq_comp;
int C_SDATA g_f_d_comp;
int C_SDATA g_f_q_comp;
int C_SDATA g_phi_control;

int C_SDATA g_voltage_err;                         

int C_SDATA g_test_speed_kp;
int C_SDATA g_test_speed_ki;
int C_SDATA g_test_speed_ymax;
int C_SDATA g_test_speed_ymin;

int C_SDATA g_test_current_kp;
int C_SDATA g_test_current_ki;
int C_SDATA g_test_current_ymax;
int C_SDATA g_test_current_ymin;
int C_SDATA g_trap_reset;
int C_SDATA g_increment_free;
int C_SDATA g_nv_start_ref0;
int C_SDATA g_nv_end_ref;
int C_SDATA g_nv_start_ref;
int C_SDATA g_speed_ref;
int C_SDATA g_encoder_pos;

unsigned int C_SDATA g_adc_start = 0xA694;
int C_SDATA g_speed_enc;
unsigned int C_SDATA g_field_w_ti;  
unsigned int C_SDATA g_circ_index;          

unsigned long C_SDATA g_voltage_err_integ;
long C_SDATA g_adc_offset_acumm;

extern struct pi_controller                                       // PI-controller parameter            
{                                                                                
    long yn;    
    int  kp;                                               // Proportional constant          
    int  ki;        
    int  ymax;                                             // Maximal ouput limit    
    int  ymin;                                             // Minimal ouput limit    
};


#if DAVECG_ENABLE_DECOUPLING

extern struct cartesian                                
{                                               
int d;                                        
int q;                                        
};

#endif

struct pi_controller C_SDATA g_pi_current_d;
struct pi_controller C_SDATA g_pi_current_q;
struct pi_controller C_SDATA g_pi_speed;                  
#if DAVECG_ENABLE_DECOUPLING 
struct cartesian C_SDATA E_dec;
#endif      
int C_SDATA F_d_dec;
int C_SDATA F_q_dec;       

unsigned int C_SDATA g_encoder_meass[32];
unsigned long C_SDATA g_time_step;
unsigned long C_SDATA g_counter1;
unsigned long C_SDATA g_ramp_up_time;
long C_SDATA g_position_ref_user;

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

#define TIME_POSITIONING (int )((float )0.75 * PULSE_FREQUENCY)
#define TIME_POSITIONING_1 (int)((float)1.05 * PULSE_FREQUENCY)
#define TIME_POSITIONING_0 TIME_POSITIONING_1 / 8
#define ANGLE_DECREMENT      (24965/TIME_POSITIONING_1)+2
#define HALF_REVOLUTION (int)ENCODER_IMP*2
#define ONE_REVOLUTION (int)ENCODER_IMP*4

//*************************************************************************************************
INLINE void TRAP_CTRL_REG_SETUP(void)
{
#if DAVECG_ENABLE_TRAP
	CCU6_TRPCTR |= 0x8000;
#endif
}

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

#if DAVECG_CURRENT_SENSE     
INLINE void ADC_DATA(int x)
{
	ADC_DAT2 = (x);
}
#endif
//****************************************************************************
// @Function        void motor_start(void) 
//
//----------------------------------------------------------------------------
void motor_start(void)
{

    long l_position_reference=0;       
    long l_position_difference=0;      

    if(g_once == 0)
    {
        g_adc_off[0] = adc_offset(2);
        g_adc_off[1] = adc_offset(4);   
        
        g_counter_positioning = 0x0;
        g_mod_index = 0x0;

	    P1L         = (P1L & 0xFFC0) | PASSIVE_STATE;	
	    ALTSEL0P1L |= 0x003F;      					

        CCU6_TCTR4 = 0x2;

#if DAVECG_ENABLE_TRAP
        CCU6_TRPCTR |= 0x8000;
#endif
        
        g_speed_ref = g_nv_start_ref;
        g_nv_start_ref0 = g_nv_start_ref;
        g_speed_enc   = 0x0;
        g_iq_comp_ref = 0x0;
        g_id_comp_ref = 0x0;
        g_i_counter   = 0x0;
        g_time_step = 0x0;
        g_counter1 = 0x0;

        g_pi_current_d.yn = 0x0;
        g_pi_current_q.yn = 0x0;
        g_pi_speed.yn     = 0x0;

        g_status_word = 0x1;
        g_once = 0x0001;
        
    }

    
} // motor_start

//****************************************************************************
// @Function        void motor_stop(void)  
//
//----------------------------------------------------------------------------
void motor_stop(void)
{
	P1L         = (P1L & 0xFFC0) | PASSIVE_STATE;	
	ALTSEL0P1L &= 0xFFC0;  		    			

    CCU6_TCTR4    = 0x050D;                                // T13 and T12 Reset/Stop, DTM Reset
    CCU6_CMPMODIF = 0x0700;                                // CC6STx outputs Reset 

    CCU6_CC60SR   = COMPARE_VALUE_CC6X;                    // CCU6 capture/compare shadow register 
                                                           // channel0  50% duty cycle                      
    CCU6_CC61SR   = COMPARE_VALUE_CC6X;                    // CCU6 capture/compare shadow register
                                                           // channel1  50% duty cycle                      
    CCU6_CC62SR   = COMPARE_VALUE_CC6X;                    // CCU6 capture/compare shadow register
                                                           // channel2  50% duty cycle                      
    CCU6_TCTR4    = 0x0040;                                // CCU6 timer control register 4 
                                                           // Shadow Tranfers enable
                         
    CCU6_TRPCTR &= 0x7FFF;                                 // CCU6 trap_enable control register
                                                           // Trap disable                      
    gb_off   = 1;                                          // Status update
    gb_on    = 0;                                          // Status update                                                                         

    if(gb_motor_status == 1)
    {
        g_once = 0x0000;
    }  
    //ROTOR ANGLE CALCULATION
      if((int)(GPT12E_T3 - g_encoder_pos) >  HALF_REVOLUTION)
      {
        g_encoder_pos += ONE_REVOLUTION;
      }
      if((int)(GPT12E_T3 - g_encoder_pos) < -HALF_REVOLUTION)
      {
        g_encoder_pos -= ONE_REVOLUTION;
      }  

} // motor_stop

//****************************************************************************
// @Function        void nv_ref_ramp(void) 
//
//----------------------------------------------------------------------------
void nv_ref_ramp(void)
{
    if(g_speed_ref < g_nv_end_ref)                         // reference ramp generation
    {                                                                         
        g_speed_ref += 1;                                       
    }                 

    if(g_speed_ref > g_nv_end_ref)                         // reference ramp generation
    {                                                                         
        g_speed_ref -= 1;                                       
    }                                                                                 

} // End of ref_ramp

//****************************************************************************
// @Function        void speed_ref_ramp(void)
//
//----------------------------------------------------------------------------
void speed_ref_ramp(void)
{
  if(g_rotor_angle_calibration == 2)
    {
        nv_ref_ramp();
    }
    
} //  End of function Speed_ref_ramp

//****************************************************************************
// @Function        void nv_ref_ramp_generation(void)
//
//----------------------------------------------------------------------------
void nv_ref_ramp_generation(void)
{
    int l_ref_difference = 0;
    long l_co_instructions = 0;


    if(g_increment_free == 1)
    {
            g_increment_free = 0;
            g_counter1 += 64;


        if(g_counter1 > g_time_step)
        {
            speed_ref_ramp();
            g_counter1 = 0;
        }
          g_nv_end_ref &= 0xFFFE;
        if(g_nv_start_ref0 != g_nv_end_ref)                // Time basis for reference ramp           
        {                                                  
#if DAVECG_KEIL
            C_CoLOAD_0_1(0, C_LSHIFT(g_nv_end_ref, 16));
            C_CoSUB_0_1(0, C_LSHIFT(g_nv_start_ref0, 16));
            C_CoABS(); 
#endif
#if DAVECG_TASKING
            l_co_instructions = (unsigned int)g_nv_end_ref; 
            _CoLOAD(l_co_instructions << 16);
            l_co_instructions = (unsigned int)g_nv_start_ref0; 
            _CoSUB(l_co_instructions << 16);
            _CoABS();
#endif

            l_ref_difference = C_CoSTOREMAS();

            if(l_ref_difference > 1)
            { 
                l_ref_difference -= 1;       
            }

            g_time_step = g_ramp_up_time  / l_ref_difference;
            g_nv_start_ref0 = g_nv_end_ref;
        }
    }
}
//****************************************************************************
// @Function        void blink_led(void)
//
//----------------------------------------------------------------------------
void blink_led(void)
{
// LED Blink
    if(g_counter0 > 32000)                                 // Load 40000 for CURRENT CTRL
    {                                                      // Load 30000 for SPEED CTRL 
#if DAVECG_XC164CS
    P1L     ^= 0x0040;                                     // USED in SPEED_CURRENT_ENC_CTRL
#endif
#if DAVECG_XC164CM
    P1L     ^= 0x0040;                                     // USED in SPEED_CURRENT_ENC_CTRL
#endif
#if DAVECG_XC167CI
    P9      ^= 0x0010;                                     // Used in all other things.
#endif
    g_counter0 = 0x0000;
    }
    g_counter0++; 

}

//****************************************************************************
// @Function        void angle_calibration(void)
//
//----------------------------------------------------------------------------
void angle_calibration()
{
    int l_phase_current_ref = 0;
    l_phase_current_ref = -(g_phase_current_ref >> 1);
            
    if(g_counter_positioning < TIME_POSITIONING_0)
    {
      g_voltage_angle = DEGREES_120;                                    
                    
      if((g_i_phase_s > (l_phase_current_ref >> 1)) && (g_mod_index < 32756))
      {
        g_mod_index += 10;
      }
      if((g_i_phase_s < ((l_phase_current_ref >> 1) - 50)) && (g_mod_index > 11))
      {
        g_mod_index -= 10;
      }
    }
    else if(g_counter_positioning < TIME_POSITIONING_1)
    { 
      if(g_voltage_angle > 0)
      {
        g_voltage_angle -= ANGLE_DECREMENT;
      }
      else
      {
        if((g_i_phase_t > l_phase_current_ref) && (g_mod_index < 32756))
        {
          g_mod_index += 10;
        }
        if((g_i_phase_t < (l_phase_current_ref - 50)) && (g_mod_index > 11))
        {
          g_mod_index -= 10;
        }
      }
    }
    else
    {
      g_rotor_angle_calibration = 0x0002;
      g_encoder_pos = 0x0000;
    }
    GPT12E_T3   = 0x0000;
    g_counter_positioning++;


}
//********************************************************************
int adc_offset(int channel)
{
    unsigned int l_i = 0;
    unsigned int l_j = 0;
    unsigned int l_k = 0;
      ADC_CIC_IE = 0;                                      //Conv service request disable
    g_adc_offset_acumm = 0;
      ADC_CTR0 = 0xA400|channel;                           // load ADC control register 0
    for(l_i = 0; l_i < 8; l_i++)
    {
        for(l_j = 0;l_j < 8192;l_j++)
        {
            ADC_CTR0_ADST = 1;
          for(l_k = 0;l_k < 80;l_k++)
            {
                NOP();
            }
        g_adc_offset_acumm += (ADC_DAT & 0x0FFC);
        }
    }
  ADC_CIC_IR = 0;                                          //Clear Conv service request flag 
  ADC_CIC_IE = 1;                                          //Conv service request enable
  ADC_CTR0  = 0xA614;                                      // load ADC control register 0
  g_adc_start = 0xA694;             
  ADC_DAT2  = 0x2000;
  return  (g_adc_offset_acumm >> 16);                      // ADC channel n 
}
//********************************************************************
