//************************************************************************************************/
// @Module              Voltage Control
// @Filename            VCH_CTRL.H
// @Controller          XC16x Series
//
//
// @Description     This file contains references for Voltage control through 
//                              Block Commutation   
//************************************************************************************************/
#ifndef _VCH_CTRL_H_
#define _VCH_CTRL_H_

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


//*************************************************************************************************
// @Macros
//*************************************************************************************************
#if DAVECG_SPEED_ENC_CTRL
#define CTRL_VAR_DECL()\
extern unsigned int C_SDATA g_speed_enc;\
extern unsigned int C_SDATA g_enc_counter;
#endif

#if DAVECG_SPEED_CURRENT_ENC_CTRL
#define CTRL_VAR_DECL()\
extern unsigned int C_SDATA g_speed_enc;\
extern unsigned int C_SDATA g_enc_counter;
#endif

#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_direction;\
    extern int C_SDATA g_once;\
    extern int C_SDATA g_i_counter;\
    extern C_BDATA g_status_word;\
	extern int C_SDATA g_current_max;\
    extern int C_SDATA g_pic_speed_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_current;\
    extern int C_SDATA g_hall_counter;\
    extern int C_SDATA g_counter0;\
    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_nv_start_ref;\
    extern unsigned int C_SDATA g_nv_ref;\
    extern unsigned int C_SDATA g_nv_end_ref;\
    extern unsigned int C_SDATA g_duty_cycle;\
    extern unsigned int C_SDATA g_speed_CC60;\
    extern unsigned int C_SDATA g_circ_index;\
    extern unsigned long C_SDATA g_ramp_up_time;\
    extern unsigned int C_SDATA g_time_measure;

   
#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);\
    extern void motor_ramp_generation(void);\
	#if DAVECG_SPEED_CALCU
    extern int speed_calculation(unsigned int time_measurement, int *speed_counter, int limit);
	#endif

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


extern int const SP_St_Tab_r_l[];
extern int const SP_Tab_r_l[];

#if DAVECG_CURRENT_SENSE
#if DAVECG_KEIL
void ADC_viError(void);
#endif
#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 == 1
#endif // CURRENT_SENSE == 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.
        } 
    }
}
//*************************************************************************************************
#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
//*************************************************************************************************
#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
//*************************************************************************************************
//*************************************************************************************************
// @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_nv_end_ref	=	MOTOR_END_REF;					   // Initialise the end reference with GUI(user) value.
	g_nv_start_ref	=	MOTOR_START_REF;				   // Initialise the start reference with GUI(user) value.
	g_ramp_up_time	=	RAMP_UP_TIME;					   // Initialise the rampup time 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_DATA(void)     
// Description		This Function specifies the ADC channel to be configured
//					in injection mode.
//-------------------------------------------------------------------------------------------------
#if DAVECG_CURRENT_SENSE       
INLINE void ADC_DATA(int x)
{
		ADC_DAT2 = (x);									   // configure the specified ADC channel in 'injection' mode.
}
#endif // CURRENT_SENSE ==1
//*************************************************************************************************
// @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.
    if(CCU6_IS & 0x2000)								   // if h/w 'hall sensor error' detected....
    {													
        gb_hs_error = 1;								   // .....then record the event into s/w flag.
        CCU6_ISR |= 0x2000;								   // and reset the h/w error bit.
    } 
    if(CCU6_IS & 0x4000)								   // if h/w 'idle state error' detected....
    { 
        gb_idle_state = 1;								   // .....then record the event into s/w flag.
        CCU6_ISR = 0x4000;								   // and reset the h/w error bit.
    }  
}
//*************************************************************************************************
//*************************************************************************************************
// @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)
{
}
//*************************************************************************************************
//*************************************************************************************************
// @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_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
}
//*************************************************************************************************
//*************************************************************************************************
// @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)
{
    CCU6_MCMOUTS = SP_Tab_r_l[((CCU6_MCMOUT & 0x3800) >> 11) + g_direction];
														   // load the Mod Pattern corresponding to the 
														   // hall pattern.
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_ADC_CTR2(void)     
// Description		This function configures the ADC control registers with 
//					with required sampling time, conversion time etc.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_ADC_CTR2(void)
{
	#if DAVECG_CURRENT_SENSE
		#if CPU_FREQUENCY <= 20
			#if DAVECG_BTS
			  ADC_CTR2 = 0x0000;						   // select the sampling time, caon=version time
			  ADC_CTR2IN = 0x0001;						   // etc for the ADC channels.
			#endif //BTS
			#if DAVECG_TLE
			  ADC_CTR2 = 0x0000;						   // select the sampling time, caon=version time 
			  ADC_CTR2IN = 0x0009;						   // etc for the ADC channels.                   
			#endif //TLE
		#endif // CPU_FREQUENCY <= 20
	#endif //CURRENT_SENSE
}
//*************************************************************************************************
//*************************************************************************************************
// @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'.
	    ADC_CTR2IN = (Y);
		temp = Z;
	#else
    ADC_CTR0 = (X);										   // initialise ADC control reg '0'.
    P5DIDIS = (Y);										   // Configure the appropriate port pins as Analog input pins.
    ADC_EIC = (Z);										   // initialise the ADC error interrupt control reg.
	#endif
}
//*************************************************************************************************

//*************************************************************************************************
//*************************************************************************************************
// @Function        void SET_ADC_FST_INT(void)     
// Description		This function configures the 'ADC_error_interrupt' as a Fast Interrupt.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void SET_ADC_FST_INT(void)
{
	#if DAVECG_CURRENT_SENSE
	#if REG_BANK_ADC == 1
	SET_FINT_CTRL_REG(ADC_viError, BNKSEL0);			   // Initialise the fast interrupt control
														   // registers such that ADC_viError is 
														   // configured as a fast interrupt. and
														   // also select 'REG BANK 0' for this 
														   // interrupt routine.
	#endif	// REG_BANK_ADC == 1
	#endif	//CURRENT_SENSE
}
//*************************************************************************************************
//*************************************************************************************************
// @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)
{
#if DAVECG_CURRENT_SENSE
	int temp;		
	ADC_CTR0 = (X);
    ADC_CTR2IN = (Y);
	temp = Z;
#else
    ADC_CTR0 = (X);
    P5DIDIS = (Y);
    ADC_EIC = (Z);
#endif 
    SET_ADC_CTR2();										   // execute the routine which configures the
														   // conversion, sampling times & resolution.
    SET_ADC_FST_INT();
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void ADC_ERR2_CBLOCK(void)     
// Description		This function implements the following:
//					1. reads motor 'current' from ADC result register.
//					2. check for 'over current' event.
//					3. buffer the samples of the graph variable by calling 'trace' function.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void ADC_ERR2_CBLOCK(void)
{
//*************************************************************
	#if DAVECG_BTS
	#if DAVECG_CURRENT_SENSE
    g_current = ((ADC_DAT2 << 3) & 0x7FFF) - g_adc_offset_res;
														   // read motor current from the ADC result reg.
	#endif // CURRENT_SENSE == 1
	#endif // BTS == 1
//*************************************************************
	#if DAVECG_TLE
	#if DAVECG_CURRENT_SENSE
	#if DAVECG_KEIL
		int l_current_aux = 0;
		l_current_aux = (ADC_DAT2 << 4) + 0x8000;		   // read motor current from the ADC result reg.
		_mac_(CoABS, 0, l_current_aux);
		g_current_max = _imac_sat_();
	#elif DAVECG_TASKING
		int l_current_aux = 0;
		long l_co_instructions = 0;
		l_co_instructions = (unsigned int)((ADC_DAT2 << 4) + 0x8000);
														   // read motor current from the ADC result reg.
		_CoLOAD(l_co_instructions << 16);
		_CoABS();
		g_current_max = _CoSTOREMAS();
	#endif // if KEIL == 1
	#endif // CURRENT_SENSE == 1
	#endif // TLE == 1
//*************************************************************************************************
    OVR_CURRENT_CHECK();
#if DAVECG_CONTROL_PANEL_ENABLE
		trace();										   // collect the samples of the graph variable.
#endif     
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void CCU6_NODEI3_CBLOCK(void)     
// Description		......
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void CCU6_NODEI3_CBLOCK(void)
{
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void CCU6_CC6SR_LOAD_VALUE(void)     
// Description		This Function initialises the CCU6 - shadow registers 
//					with appropraite count values.
//-------------------------------------------------------------------------------------------------
INLINE void CCU6_CC6SR_LOAD_VALUE(void)
{
	#if DAVECG_BTS       
	CCU6_CC61SR  =  10;
	CCU6_CC62SR  =  CCU6_CC61SR + T13_TIME;
	#elif DAVECG_TLE
	CCU6_CC61SR  =  0;
	CCU6_CC62SR  =  CCU6_CC61SR + T13_TIME;
	#endif

}
//*************************************************************************************************
//*************************************************************************************************
// @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)
{
	motor_ramp_generation();
}
//*************************************************************************************************
#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)
{
    g_speed_CC60 = speed_calculation(CCU6_CC60R, &g_hall_counter, (6*PP));
    													   // get the present 'speed'.
    if (g_hall_counter < (LIMIT_C)) 					   // if motor speed is too small....
    {
        g_speed_CC60 = 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(0xA603, 0x0042, 0x0030);			   // execute ADC initialisation routines.
		#else
		ADC_INIT3_CBLOCK2(0x0000, 0x0000, 0x0030);			   // execute ADC initialisation routines.
		#endif
	#endif

	#if DAVECG_TLE
		#if DAVECG_CURRENT_SENSE
		ADC_INIT3_CBLOCK2(0xA605, 0x0053, 0x0030);			   // execute ADC initialisation routines.
		#else
		ADC_INIT3_CBLOCK2(0x0000, 0x0000, 0x0030);			   // execute ADC initialisation routines.
		#endif
	#endif
}
//*************************************************************************************************
//*************************************************************************************************
#endif // _CTRL_H_
