//*************************************************************************************************
// @Module              Current Control Bemf
// @Filename            CCB_CTRL.H
// @Controller          XC16x Series
//
//
// @Description   This file contains references for Current control through 
//                              Block Commutation   
//*************************************************************************************************
#ifndef _CCB_CTRL_H_
#define _CCB_CTRL_H_

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

//*************************************************************************************************
// @Defines
//*************************************************************************************************
struct pi_controller                                       // PI-controller parameter            
{                                                                                
    long yn;											   // PI integral buffer    
    int  kp;                                               // Proportional constant          
    int  ki;											   // Integral constant
    int  ymax;                                             // Maximal ouput limit    
    int  ymin;                                             // Minimal ouput limit    
};

//*************************************************************************************************
// @Macros
//*************************************************************************************************
#define CTRL_VAR_DECL()\
    extern BIT gb_motor_status;\
    extern BIT gb_hs_error;\
    extern BIT gb_ctrap;\
    extern BIT gb_time_out;\
    extern BIT gb_overcurrent;\
    extern BIT gb_idle_state;\
    extern int C_SDATA g_adc_mem;\
    extern int C_SDATA g_direction;\
    extern int C_SDATA g_once;\
    extern int C_SDATA g_i_counter;\
    extern C_BDATA g_status_word;\
	extern unsigned char C_SDATA injection_channel_select;\
    extern int C_SDATA g_current_max;\
    extern int C_SDATA g_pi_controller_out;\
    extern int C_SDATA g_trap_reset;\
    extern long C_SDATA g_adc_offset_res;\
    extern int C_SDATA g_increment_free;\
    extern int C_SDATA g_test_kp;\
    extern int C_SDATA g_test_ki;\
    extern int C_SDATA g_test_ymax;\
    extern int C_SDATA g_test_ymin;\
    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_current_ref;\
    extern int C_SDATA g_current;\
    extern int C_SDATA g_i_mpattern;\
    extern int C_SDATA g_counter0;\
    extern int C_SDATA g_volt_increment;\
    extern int C_SDATA g_freq_increment;\
    extern int C_SDATA g_speed_counter;\
    extern int C_SDATA g_limit;\
	extern int C_SDATA g_direction_user;\
    extern unsigned int C_SDATA g_bemf_check_freq;\
    extern unsigned int C_SDATA g_bemf_end_freq;\
    extern unsigned int C_SDATA g_start_duty_c;\
    extern unsigned int C_SDATA g_duty_cycle;\
    extern unsigned int C_SDATA g_speed_CC61;\
    extern unsigned int C_SDATA g_state;\
    extern unsigned int C_SDATA g_slope;\
    extern unsigned int C_SDATA g_bemf_aux;\
    extern unsigned int C_SDATA g_adc_ctr_bemf;\
    extern unsigned int C_SDATA g_circ_index;\
	extern unsigned int C_SDATA g_start_freq;\
    extern struct pi_controller C_SDATA g_pi_array;\
    extern struct pi_controller C_SDATA g_pi_current_array;\
    extern unsigned int C_SDATA g_time_measure;\
	extern unsigned int C_SDATA COMPARE_VALUE;\
	extern unsigned int C_SDATA HIGH_LIMIT;\
	extern unsigned int C_SDATA LOW_LIMIT;

#define CTRL_FUNC_DECL()\
    extern void motor_start(void);\
    extern void motor_stop(void);\
    extern void commutation_init(void);\
    extern void init_control(void);\
    extern void commutation(void); \
    extern void duty_cycle_update(void);\
    extern void blink_led(void);\
    extern void adc_offset(void);\
	#if DAVECG_SPEED_CALCU
    extern int speed_calculation(unsigned int time_measurement, int *speed_counter, int limit);\
	#endif
    extern int pi_controller64(long *pi_parameter,int reference,int actual);
//*************************************************************************************************
#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 // 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 // TASKING

//*************************************************************************************************
#if DAVECG_TASKING
#if REG_BANK_ADC == 1
interrupt (ADC_E_INT) _localbank(-1)_cached void ADC_viError(void);
#endif 
#if REG_BANK_ADC == 2
interrupt (ADC_E_INT) using (Reg_bank_ADC) void ADC_viError(void);
#endif
#endif // TASKING

//*************************************************************************************************
CTRL_VAR_DECL()
CTRL_FUNC_DECL()
#if DAVECG_CONTROL_PANEL_ENABLE
COMM_FUNC_DECL()
#endif
//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_CC2_REG(void)     
// Description		This Function initialises the CC2 control registers with appropriate values.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_CC2_REG(void)
{
#if DAVECG_BTS
    SRCP2		=	C_SEG(g_adc_ctr_bemf);				   // Initialise the PEC CH2 source pointer.
    DSTP2		=	C_SOF(ADC_CTR0);					   // Initialise the PEC CH2 dest pointer.
    CC2_T7      =	T7_PERIOD;							   // Initialise CC2_T7 timer.
    CC2_T7REL   =	T7_PERIOD;							   // specify the reload value for CC2_T7.
    CC2_CC19    =	CC19_VALUE;							   // Initialise CC2 channel 19.
    CC2_CC31    =	CC31_VALUE;							   // Initialise CC2 channel 31.
#elif DAVECG_TLE
    SRCP2		=	C_SEG(g_adc_ctr_bemf);				   // Initialise the PEC CH2 source pointer.
    DSTP2		=	C_SOF(ADC_CTR0);					   // Initialise the PEC CH2 dest pointer. 
    REFRESH_CODE_BLOCK();								   // execute driver 'refresh' routine.
    CC2_T7      =	T7_PERIOD; 							   // Initialise CC2_T7 timer.               
    CC2_T7REL   =	T7_PERIOD; 						       // specify the reload value for CC2_T7.   
    CC2_CC19    =	CC19_VALUE;						       // Initialise CC2 channel 19.              
    CC2_CC31    =	CC31_VALUE;						       // Initialise CC2 channel 31.             
#endif // if (BTS == 1) && (BEMF == 1)
}
//*************************************************************************************************

#define		REQUESTED				1
#define		RESET					0
#define		MOTOR_READY_TO_START	0
#define		MOTOR_STOPPED			1
//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_TRAP_STATUS(void)     
// Description		This Function will set the s/w 'trap' flag.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_TRAP_STATUS(void)
{
	gb_ctrap = 1;										   // set the s/w trap flag to indicate 
														   // the detection of 'CTRAP'
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void TIME_OUT(void)     
// Description		This Function will set the s/w 'time out' flag.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void TIME_OUT(void)
{
	gb_time_out  = 1;									   // set the s/w time out flag to indicate  
														   // the detection of 'Time out'           
}

//*************************************************************************************************
//*************************************************************************************************
// @Function        void OVR_CURRENT_CHECK(void)     
// Description		This Function implements the logic required for 'over current' detection.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void OVR_CURRENT_CHECK(void)
{
    if (g_current >= CURRENT_MAX)						   // motor instantaneous current higher than
    {													   // specified limit ?
        g_i_counter++;									   // if yes, increment s/w counter.
        if (g_i_counter == TIME_CURRENT_MAX)			   // s/w counter reached the specified limit ?
        {
            motor_stop();								   // if yes, then stop the motor.
            gb_motor_status = 1;						   // Set the 'motor status' flag to convey 
														   // to the control panel that motor has been stopped.
            gb_overcurrent = 1;							   // Set the 'overcurrent' flag to convey 
														   // the same to the control panel
        }
    }
    else												   // if motor 'current' sample is not higher
    {													   // than the specified limit....
        if (g_i_counter > 0)							   // then.....
        {
            g_i_counter--;								   // ....decrement the s/w counter.
        }
    }
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void TRAP_RESET(void)     
// Description		This Function will Unlatch/Reset the 'trap' flag if requested.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void TRAP_RESET(void)
{
    if (g_trap_reset == REQUESTED)						   // 'trap' reset requested ?
    { 
        g_trap_reset	= RESET;						   // if yes, acknowledge the request....
        gb_ctrap		= RESET;						   // ...and reset the s/w 'trap' flag.
    }
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void MOTOR_OPERATION_CONTROL(void)     
// Description		This Function will start or stop the motor depending on present inputs.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void MOTOR_OPERATION_CONTROL(void)
{
    if (gb_ctrap)										   // 'TRAP' event recorded ?
    {													   // if yes.....
        gb_motor_status = MOTOR_STOPPED;				   // ....then stop the motor.
    } 
    else												   // otherwise....
    { 
        if (gb_motor_status == MOTOR_READY_TO_START)	   // ....motor start requested by user ?
        {												   // if yes.....
            motor_start();								   // execute motor_start routine.
        } 
        else											   // if not requested....
        { 
            motor_stop();								   // then execute motor_stop routine.
        } 
    }
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void CONTROL_PANEL_PARAMS(void)     
// Description		This Function loads the values entered by the user in the 'Run Time Control Panel'
//					dialog of DID into the appropriate target variables. 
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void CONTROL_PANEL_PARAMS(void)
{
    g_trap_reset	=	1;								   // set the 'trap_reset' s/w flag so that 
														   // s/w 'trap' flag is cleared under power ON.
    gb_ctrap		=	0;								   // clear the s/w trap flag to begin with.
    g_current_ref	=	MOTOR_CURRENT_REF;				   // Initailise the 'Current_ref' with 
														   // GUI(user) value.
	g_direction_user=	MOTOR_DIRECTION;				   // Initialise the motor direction variables
	g_direction		=	g_direction_user * 8;			   // with GUI(user) specified direction.
	#if DAVECG_CONTROL_PANEL_ENABLE
	gb_motor_status	=	1;								   // set the motor_status flag if motor
														   // start not requested by GUI(user).
	#else
	gb_motor_status =	0;								   // clear the motor_status flag if motor
														   // start is requested by GUI(user).
	#endif
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void ADC_OFFSET(void)     
// Description		This function computes the ADC offset value, by taking 
//					65,535 samples of the ADC measured data. This computed
//					offset value is preserved in the variable g_adc_offset_res.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void ADC_OFFSET(void)							    
{
	#if DAVECG_CURRENT_SENSE
		adc_offset();									   // compute 'adc_offset' value.
	#endif // CURRENT_SENSE ==1
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_MONITOR_STATUS(void)     
// Description		This function executes the motor_stop routine and conveys the same to 
//					the control panel by setting the motor_status s/w flag.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_MONITOR_STATUS(void)
{
    motor_stop();										   // execute motor_stop routine.
    gb_motor_status = 1;								   // set the motor_status s/w flag to 
														   // convey to the control panel that 
														   // motor has been stopped.
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void RESET_CCU6_WHE(void)     
// Description		This function clears the 'wrong hall event' h/w flag.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void RESET_CCU6_WHE(void)
{
}

//*************************************************************************************************
//*************************************************************************************************
// @Function        void BEMF_PARAM_INIT(void)     
// Description		This function loads the user entered values for back EMF start-up parameters
//					from the Run time control panel dialog of DID into the corresponding 
//					target variables.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void BEMF_PARAM_INIT(void)
{
    g_bemf_check_freq  = BEMF_CHECK_FREQ;				   // initialise 'bemf check freq' with GUI(user) value.
    g_bemf_end_freq    = END_FREQUENCY;				       // initialise 'bemf end freq' with GUI(user) value.
    g_freq_increment   = FREQ_INC;						   // initialise 'bemf freq increment' with GUI(user) value.
    g_volt_increment   = VOLT_INC;						   // initialise 'bemf volt  increment' with GUI(user) value.
	g_start_duty_c     = START_DUTY_CYC;				   // initialise 'bemf start duty cycle' with GUI(user) value.
	g_start_freq       = START_FREQ;					   // initialise 'bemf start frequency' with GUI(user) value.
}

//*************************************************************************************************
//*************************************************************************************************
// @Function        void ADC_AUX_BEMF(void)     
// Description		This function determines which of the three motor phases is presently 
//					not activated, and sets the corresponding ADC channel for Zero crossing detection.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void ADC_AUX_BEMF(void)
{
	#if DAVECG_CURRENT_SENSE
	if((g_bemf_aux == BEMF_AUX_VAL11) || (g_bemf_aux == BEMF_AUX_VAL12)) 
    {													   // if phase '1' is Inactive....
        g_adc_ctr_bemf = BEMF_CTRL_VAL1;				   // ....then set ADC CH1 for Zero Cross Detection.
    } 
    if((g_bemf_aux == BEMF_AUX_VAL21) || (g_bemf_aux == BEMF_AUX_VAL22)) 
    {													   // if phase '2' is Inactive.... 
        g_adc_ctr_bemf = BEMF_CTRL_VAL2;				   // ....then set ADC CH2 for Zero Cross Detection. 
    } 
    if((g_bemf_aux == BEMF_AUX_VAL31) || (g_bemf_aux == BEMF_AUX_VAL32)) 
    {													   // if phase '3' is Inactive.... 
        g_adc_ctr_bemf = BEMF_CTRL_VAL3;				   // ....then set ADC CH3 for Zero Cross Detection. 
    }
	#endif
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void INIT_PI_VAR(void)     
// Description		This function initialises the PI gain & Limit variables with the corresponding 
//					user entered values from the Run time control panel dialog of DID.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void INIT_PI_VAR(void)
{
    g_pi_array.ymax  = PIC_YMAX;						   // Initialise the PI upper limit variable. 
    g_pi_array.ymin  = PIC_YMIN;						   // Initialise the PI lower limit variable. 
    g_pi_array.kp    = INIT_CURRENT_KP;					   // Initialise the PI proportional gain variable. 
    g_pi_array.ki    = INIT_CURRENT_KI;					   // Initialise the PI integral gain variable. 
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void INIT_CTRL_VAR(void)     
// Description		This function initialises the various intermediate variables that are required to 
//					be set to pre-defined default values before any motor related operation.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void INIT_CTRL_VAR(void)
{
    g_start_duty_c	 =	0x0;							   // Initialize BEMF start_duty_cycle to '0'.
    g_direction		 =	0x0;							   // Initialise default motor direction to 'clockwise'.
    g_once			 =	0x0;							   // Clear the variable 'once' so that by default 
														   // motor stop is assumed.
    g_status_word	 =	0x0002;							   // Initialise status flags to reflect motor stopped condition.
	INIT_PI_VAR();										   // execute PI initialisation routine.
	#if DAVECG_BLOCK_COMMUTATION
	CONTROL_PANEL_PARAMS();								   // execute control panel dependent variable initialisation routine.
	#endif
	#if DAVECG_BEMF
	BEMF_PARAM_INIT();									   // execute Back EMF related variable initialisation routine.
	#endif
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void MCMOUT_UPDATE(void)     
// Description		This function loads the appropriate 'modulation pattern' into the MCMOUTS register.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void MCMOUT_UPDATE(void)
{

}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_ADC_SRC_DST_PTR(void)     
// Description		This function initialises the PEC channel 7 source & destination pointers
//					with appropriate variables.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_ADC_SRC_DST_PTR(void)
{
    SRCP7 = C_SOF(ADC_DAT);								   // point the source pointer to ADC result register.
    DSTP7 = C_SOF(g_adc_mem);							   // point the destination pointer to global variable.
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_ADC_CTR0(void)     
// Description		This function initialises the ADC control registers with 
//					with appropriate values.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_ADC_CTR0(unsigned int X, int Y, int Z)
{
	#if DAVECG_CURRENT_SENSE
		int temp;
		ADC_CTR0 = (X);									   // initialise ADC control reg '0'.
		temp = Y;
		temp = Z;
	#else
    ADC_CTR0 = (X);										   // initialise ADC control reg '0'.
    ADC_EIC = (Y);										   // initialise the ADC error interrupt control reg.
    P5DIDIS = (Z);										   // Configure the appropriate port pins as Analog input pins.
	#endif // CURRENT_SENSE == 1
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_ADC_CTR2(void)     
// Description		This function initialises the ADC control register and ADC injection 
//					mode control reg with conversion time, sampling time etc.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_ADC_CTR2(void)
{
	#if CPU_FREQUENCY <= 20
    ADC_CTR2	= 0x0000;								   // select the conversion time, sampling time 
														   // and resolution of the ADCs.
    ADC_CTR2IN	= 0x0000;								   // select the Injection mode -conversion time, 
														   // sampling time and resolution of injection 
														   // channels.
	#endif // CPU_FREQUENCY <= 20
}

//*************************************************************************************************
//*************************************************************************************************
// @Function        void ADC_INIT3_CBLOCK2(void)     
// Description		This function executes the routines which initialise the ADC control registers.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void ADC_INIT3_CBLOCK2(unsigned int X, int Y, int Z)
{
    SET_ADC_SRC_DST_PTR();								   // execute PEC channel source & dest pointer 
														   // initialisation routine.
    SET_ADC_CTR2();										   // execute the routine which configures the
														   // conversion, sampling times & resolution.
    SET_ADC_CTR0(X, Y, Z);								   // execute the routine which selects the Mode
														   // of operation, Interrupts, etc for ADCs.
}
//*************************************************************************************************
//*************************************************************************************************
#if DAVECG_TLE
//*************************************************************************************************
// @Function        void ADC_ERR2_SWITCH_CH_CBLOCK2(void)     
// Description		This function determines the ADC channel to be injected.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void ADC_ERR2_SWITCH_CH_CBLOCK2(void)
{
    l_current_aux = (CCU6_MCMOUT & 0x003F);				   // read the present Modulation Pattern.
    if(g_i_mpattern != l_current_aux)					   // if there is a change in the mod pattern......
    {													   // ........
        g_i_mpattern = l_current_aux;					   // preserve the present Mod Pattern.
        if(((g_i_mpattern == 0x0012) || (g_i_mpattern == 0x0018)) || (g_i_mpattern == 0x0021))
        {												   // .....????????.......
            ADC_DAT2 = 0x5000;							   // Select ADC CH 5 for Injection.
        }
        else
        {
            ADC_DAT2 = 0x4000;							   // Select ADC CH 4 for Injection.
        }
    }
}
#endif // TLE == 1
//*************************************************************************************************
//*************************************************************************************************
// @Function        void CCU6_NI2_BEMF_SLOPE_CBLOCK0(void)     
// Description		This function specifies whether we need to look for 'rising' edge
//					or 'falling' edge of the Back EMF signal.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void CCU6_NI2_BEMF_SLOPE_CBLOCK0(void)
{
    if (g_slope == 2)									   // ...???......
    {
        g_slope = 0;									   // we need to look for 'rising' edge.
    }
    if (g_slope == 3)									   // ...???.....
    {	
        g_slope = 1;									   // we need to look for 'falling' edge.
    }
}
//*************************************************************************************************
// @Function        void GPT1_TMR22_CBLOCK0(void)     
// Description		This function initialises the local variable used in GPT interrupt routine.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void GPT1_TMR22_CBLOCK0(void)
{
	#if DAVECG_KEIL
	int l_enc_aux = 0;
	#elif DAVECG_TASKING
	long l_co_load = 0;
	#endif
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void DUTY_CYC_UPDATE(void)     
// Description		This function ensures that the computed 'duty cycle' is within upper & lower 
//					limits and then loads the same into the CCU6 channel 3 shadow register.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void DUTY_CYC_UPDATE(void)
{
	#if DAVECG_KEIL
	C_CoLOAD_1_0(g_duty_cycle, 0);						   // load the 'duty cycle' into MAC accumulator.
    C_CoMIN_1_0(DUTY_CYCLE_MAX, 0);						   // duty cycle should always be less than upper limit.
    C_CoMAX_1_0(DUTY_CYCLE_MIN, 0);						   // duty cycle should always be higher than lower limit.
   CCU6_CC63SR = _lmac_();								   // load the saturated duty cycle value into CCU6 CH3 SR.
	#endif
	#if DAVECG_TASKING
    Int_CoLimit(0,g_duty_cycle,DUTY_CYCLE_MIN,DUTY_CYCLE_MAX);
														   // load the duty cycle into MAC acc and saturate....
    CCU6_CC63SR = _CoSTOREMAS();						   // load the saturated duty cycle value into CCU6 CH3 SR.
	#endif
    CCU6_TCTR4 = 0x4000;								   // reset and re-start CCU6 T13 timer.
	g_increment_free = 1;								   // set the s/w flag as an acknowledgement to other 
														   // routines that duty cycle has been updated.
}
//*************************************************************************************************
INLINE void GPT1_TMR22_CBLOCK(void)
{
}
//*************************************************************************************************
INLINE void GPT1_TMR25_CBLOCK(void)
{
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_PI_VAR(void)     
// Description		This function transfers the user entered PI gains into the corresponding 
//					target variables.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_PI_VAR(void)
{
    g_pi_array.kp   = g_test_kp;						   // update the PI prop gain with latest user value.
    g_pi_array.ki   = g_test_ki;						   // update the PI integral gain with latest user value.
    g_pi_array.ymax = g_test_ymax;						   // update the PI upper limit with latest user value.
    g_pi_array.ymin = g_test_ymin;						   // update the PI lower limit with latest user value.
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void MOTOR_RAMP_GEN(void)     
// Description		This function implements the initial ramp of motor start operation.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void MOTOR_RAMP_GEN(void)
{
}
//*************************************************************************************************
#if DAVECG_SPEED_CALCU
//*************************************************************************************************
// @Function        void CCU6_NI2_SPEED_CAL_CBLOCK(void)     
// Description		This function calls the 'speed calculation' routine to get the present motor speed.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------

INLINE void CCU6_NI2_SPEED_CAL_CBLOCK(void)
{
    if (g_state == 3)									   // if motor is running in steady state( state 3)...
    {
        g_speed_CC61 = speed_calculation(g_time_measure, &g_speed_counter, (6*PP));
    }													   // ....then get the present 'speed'.

    if (g_speed_counter < (LIMIT_C))					   // if motor speed is too small....
    {
        g_speed_CC61 = 0;								   // ....then reset speed to '0'.
    }
}
//*************************************************************************************************
#endif
//*************************************************************************************************
// @Function        void ADC_INIT3_CBLOCK(void)     
// Description		This function Initialises the ADC control registers.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void ADC_INIT3_CBLOCK(void)
{
	#if DAVECG_BTS
	#if DAVECG_CURRENT_SENSE
	ADC_INIT3_CBLOCK2(0x9603, 0x0028, 0x000E);			   // execute ADC initialisation routines.
	#else
	ADC_INIT3_CBLOCK2(0x8200, 0x0028, 0x000E);			   // execute ADC initialisation routines.
	#endif
	#endif 	//BTS
	
	#if DAVECG_TLE
	#if DAVECG_CURRENT_SENSE
	ADC_INIT3_CBLOCK2(0x9604, 0x0028, 0x000E);			   // execute ADC initialisation routines.
	#else
	ADC_INIT3_CBLOCK2(0x8201, 0x0028, 0x000E);			   // execute ADC initialisation routines.
	#endif

	#endif	//TLE
	
}
//*************************************************************************************************

//*************************************************************************************************
// @Function        void ADC_ERR2_CBLOCK(void)     
// Description		This function implements the following:
//					1. reads motor 'current' from ADC result register.
//					2. Then call 'PI controller' algorithm to compute new duty cycle.
//					3. update new duty cycle into the compare register and
//					4. check for 'over current' event.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void ADC_ERR2_CBLOCK(void)
{
   		#if DAVECG_CURRENT_SENSE
		
			#if DAVECG_BTS			
	//********************************************************************
		#if DAVECG_XC164CS
		if ((ADC_CTR0_ADBSY == 0)&&(ADC_CTR0_ADCRQ==0) && (ADC_CTR0_SMPL==0))
		#endif
		#if DAVECG_XC164CM
		if ((ADC_CTR0_ADBSY == 0)&&(ADC_CTR0_ADCRQ==0) && (ADC_CTR0_SAMPLE==0))
		#endif
		{
	  	injection_channel_select = (unsigned char)((ADC_DAT2 >> 8)&0x00f0);
	  	if(injection_channel_select == 0x30)
	  	{
	  	g_current 	= ((ADC_DAT2 << 3) & 0x7FFF) - g_adc_offset_res;
	  	ADC_DAT2 	&= 0x0fff;
	  	ADC_DAT2 	|= 0x4000;
	  	}
	  	else if(injection_channel_select==0x40)
	  	{
	  	COMPARE_VALUE 	 = (ADC_DAT2 & 0x0FFC);
	  	COMPARE_VALUE	=	COMPARE_VALUE>>1;
	  	ADC_DAT2 		&= 0x0fff;
	  	ADC_DAT2 		|= 0x3000;
		HIGH_LIMIT	=	COMPARE_VALUE + (COMPARE_VALUE >> 4); 
		LOW_LIMIT	=	COMPARE_VALUE - (COMPARE_VALUE >> 4);
	  	}
	  	}

	//************************************************************************
			#endif	//BTS
		
			#if DAVECG_TLE
				#if DAVECG_KEIL
				int l_current_aux = 0;
		    	_push_(MCW);

    		l_current_aux = (ADC_DAT2 << 4) + 0x8000;	   // read motor 'current' from ADC result register. 
		    _mac_(CoABS, 0, l_current_aux);				   
		    g_current_max = _imac_sat_();
	    	MCW = 0x0600;
		        C_CoMULu(((PULSE_PERIOD - g_duty_cycle) << CURRENT_FACTOR), CURRENT_CONSTANT);
				    C_CoMUL(l_current_aux, C_CoSTOREMAS());
				    g_current = C_CoSTOREMAS();
				#elif DAVECG_TASKING
		    int l_current_aux = 0;
		    long l_co_instructions = 0;
		    l_co_instructions = (unsigned int)((ADC_DAT2 << 4) + 0x8000);
		    _CoLOAD(l_co_instructions << 16);		       // read motor 'current' from ADC result register. 
		    _CoABS();
		    g_current_max = _CoSTOREMAS();
	    	MCW = 0x0600;
		        C_CoMULu(((PULSE_PERIOD - g_duty_cycle) << CURRENT_FACTOR), CURRENT_CONSTANT);
  				  C_CoMUL(l_current_aux, C_CoSTOREMAS());
				    g_current = C_CoSTOREMAS();
				#endif	//KEIL_TASKING

			#endif	//TLE
        if (g_state == 3)								   // if motor is running in steady state....
		    {
        	g_pi_controller_out = pi_controller64(&g_pi_array.yn, g_current_ref, g_current);
														   // then execute PI control algorithm to get new duty cycle.
	        g_duty_cycle = PULSE_PERIOD - g_pi_controller_out;
														   // map the new dutycycle onto the PWM period scale.
    		}
			#endif	//CURRENT_SENSE

    	DUTY_CYC_UPDATE();								   // load the computed duty cycle into the appropriate compare register.
	    OVR_CURRENT_CHECK();							   // verify whether present motor 'current' is hgher than the specified limit.
			#if DAVECG_TLE
			#if DAVECG_CURRENT_SENSE
			ADC_ERR2_SWITCH_CH_CBLOCK2();
    		#if DAVECG_KEIL
				MCW = _pop_();
			#endif	//KEIL

			#endif	//CURRENT_SENSE
			#endif	//TLE

}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void CCU6_NODEI3_LOCAL_VAR(void)     
// Description		This function initialises the local variable used in CCU6 interrupt routine..
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void CCU6_NODEI3_LOCAL_VAR(void)
{
	int l_bemf_aux = 0;									   // declare & initialise the local variable.
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void CCU6_NODEI3_CBLOCK(void)     
// Description		This function implements the following:
//					1. Takes the motor into 'steady' state through 'transient' state by executing 
//						"commutation" function.	
//					2.	Dynamically determines which motor 'phase' need to be looked for Zero crossing signal.
//					3.	executes sampling/ trace of the graph variable.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void CCU6_NODEI3_CBLOCK(void)
{
		int l_bemf_aux = 0;
		#if DAVECG_BTS
		commutation();									   // execute the motor transient/ steady state routines.
		#endif	//BTS
		#if DAVECG_TLE
			#if DAVECG_ENABLE_REFRESH_PULSE
			PECC0 = 0x0001;
			#endif // ENABLE_REFRESH_PULSE == 1
	    commutation();									   // execute the motor transient/ steady state routines.
		#endif	//TLE
 		l_bemf_aux = (CCU6_MCMOUT & 0x003F);			   // read the present Modulation Pattern....
		if(g_bemf_aux != l_bemf_aux)					   // ...compare it with previous Mod Pattern.....
	    {												   // if Mod Pattern has changed......
        g_bemf_aux = l_bemf_aux;						   // then preserve present Mod Pattern...
        ADC_AUX_BEMF();									   // ....and determine the next ADC channel for Zero crossing sensing.
		}
 		#if DAVECG_CONTROL_PANEL_ENABLE
		trace();										   // buffer the samples of the variable selected for graph plotting.
		#endif 
}
//*************************************************************************************************
#endif // _CURRENT_CTRL_H_
