//*****************************************************************************/
// @Module         FOC Position Control
// @Filename            CTRL.C
// @Controller     XC16x Series
//
//
// @Description    This file contains functions for position control 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 speed_ref_ramp(void);
void angle_calibration(void);
int pi_con_pos_co(int *pi_parameter,int reference,int actual);
int clarke_trans_co(int I_phase_s, int I_phase_t , int *ia);
int park_trans_co(int e_a,int e_b,int phi,int *a_b);
int cart_polar_conv_co(int real,int imaginar,int *phase);
int P_controller_co(long *x,int Kp);
long generator_co(long *x,long y);

//****************************************************************************
// @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_ramp_cte;
int C_SDATA g_speed_ref_max;

int C_SDATA g_rotor_angle_calibration;
int C_SDATA g_phi_rotor;
int C_SDATA g_voltage_vector;
int C_SDATA g_counter_positioning;
int C_SDATA g_phase_current_ref;
int C_SDATA g_phi_rotor_mem;

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_encoder_mem; 
int C_SDATA g_position_rel;     
int C_SDATA g_position_rel_mem; 

int C_SDATA g_test_position_k;
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_speed_ref;
unsigned int C_SDATA g_adc_start = 0xA694;

int C_SDATA g_speed_enc;
unsigned int C_SDATA g_circ_index;          

long C_SDATA g_adc_offset_acumm;

extern 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                    

};

extern struct control_input                                 
{                                                                                
    long reference;                                       
    long actual;                                          
};

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

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;                  
struct integral C_SDATA generator;        

unsigned int C_SDATA g_encoder_meass[16];
long C_SDATA g_position_ref_0;
long C_SDATA g_position_ref_user;

struct control_input C_SDATA g_position;

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

#define TIME_POSITIONING (int )((float )0.75 * PULSE_FREQUENCY)
#define TIME_POSITIONING_0   (int)  ((float)0.3  * PULSE_FREQUENCY)
#define TIME_POSITIONING_1   (int)  ((float)0.75 * PULSE_FREQUENCY)
#define ANGLE_DECREMENT_0    (24965/TIME_POSITIONING_0)+2
#define ANGLE_DECREMENT_1    (24965/TIME_POSITIONING_1)+2

//*************************************************************************************************
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;

        g_voltage_vector = 0x0;

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


        CCU6_TCTR4 = 0x2;

#if DAVECG_ENABLE_TRAP
        CCU6_TRPCTR |= 0x8000;
#endif
        
        g_speed_ref = 0x0;
        g_speed_enc   = 0x0;
        g_iq_comp_ref = 0x0;
        g_id_comp_ref = 0x0;
        g_i_counter   = 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;
        
    }

    C_CoLOAD(g_position.actual);
    C_CoSUB(g_position_ref_user);
    l_position_difference = C_CoSTORE();
    C_CoABS();
    l_position_reference = C_CoSTORE();
    if(l_position_reference <= (1 << POSITION_EXP))
    {
        g_position_ref_user    += l_position_difference;
    }
    
} // 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;
    }  


} // motor_stop

//****************************************************************************
// @Function        void nv_ref_ramp_generation(void) 
//
//----------------------------------------------------------------------------
void nv_ref_ramp_generation(void)
{

}

//****************************************************************************
// @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(void)
{
    int l_phase_current_ref = 0;
    l_phase_current_ref = -(g_phase_current_ref >> 1);
    switch(g_voltage_vector)
    {
    case 0:
        {
            g_voltage_angle = DEGREES_0;
            if((g_i_phase_t > (l_phase_current_ref >> 1)) && (g_mod_index < 32756))
            {
                g_mod_index += 10;
            }
            if((g_i_phase_t < ((l_phase_current_ref >> 1) - 50)) && (g_mod_index > 11))
            {
                g_mod_index -= 10;
            }
            if(g_counter_positioning > TIME_POSITIONING_0)
            {
                g_counter_positioning = 0;
                g_voltage_angle = DEGREES_0 - 1;
                g_voltage_vector = 1;
            }
            break;
        }
    case 1:
        {
             if((unsigned)g_voltage_angle > (unsigned)DEGREES_240)
              {
                g_voltage_angle -= ANGLE_DECREMENT_0;
              }
            if(g_counter_positioning > TIME_POSITIONING_0)
            {
                g_counter_positioning = 0;
                g_voltage_vector = 2;
            }
            break;
        }
    case 2:
        {
              if(((unsigned)g_voltage_angle) > DEGREES_120)
              {
                g_voltage_angle -= ANGLE_DECREMENT_0;
              }
            if(g_counter_positioning > TIME_POSITIONING_0)
            {
                g_counter_positioning = 0;
                g_voltage_vector = 3;
            }
            break;
        }
    case 3:
        {
              if(g_voltage_angle > DEGREES_0)
              {
                g_voltage_angle -= ANGLE_DECREMENT_1;
              }
      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;
            }
            if(g_counter_positioning > TIME_POSITIONING_1)
            {
                g_rotor_angle_calibration = 2;
                g_mod_index = 0;
            }
            g_phi_rotor_mem     = g_position.actual;
            g_position_ref_user = g_position.actual;
            g_position_ref_0    = g_position.actual;
      }
            break;
        }
    default:{}
    }
    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 
}
//********************************************************************
