//************************************************************************************************/
// @Module              Speed Current Control
// @Filename            SCCH_CTRL.H
// @Controller          XC16x Series
//
//
// @Description     This file contains references for SpeedCurrent control  
//                              through Block Commutation   
//************************************************************************************************/
#ifndef _SCCH_CTRL_H_
#define _SCCH_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_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_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;\
    extern int C_SDATA g_hall_counter;\
    extern int C_SDATA g_counter0;\
    extern int C_SDATA g_limit;\
    extern int C_SDATA g_pic_current_out;\
	extern int C_SDATA g_direction_user;\
    extern unsigned int C_SDATA g_nv_start_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_speed_ref;\
    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 long C_SDATA g_ramp_up_time;\
    extern struct pi_controller C_SDATA g_pi_speed_array;\
    extern struct pi_controller C_SDATA g_pi_current_array;\
    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);\
    extern int speed_calculation(unsigned int time_measurement, int *speed_counter, int limit);\
    extern int pi_controller64(long *pi_parameter,int reference,int actual);

//*************************************************************************************************
#define CONDITION_OPERATOR >

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_KEIL
void ADC_viError(void);
#endif// DAVECG_KEIL

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

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

//*************************************************************************************************
//*************************************************************************************************
// @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_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) 
{
    g_pi_speed_array.ymax		= PIC_SPEED_YMAX; 		   // Initialise the speed PI upper limit variable.   
    g_pi_speed_array.ymin		= PIC_SPEED_YMIN;		   // Initialise the speed PI lower limit variable.   
    g_pi_speed_array.kp			= INIT_SPEED_KP;		   // Initialise the speed PI proportional gain variable.
    g_pi_speed_array.ki			= INIT_SPEED_KI;		   // Initialise the speed PI integral gain variable.    
	g_pi_current_array.ymax		= PIC_CURRENT_YMAX; 	   // Initialise the current PI upper limit variable.      
    g_pi_current_array.ymin		= PIC_CURRENT_YMIN;		   // Initialise the current PI lower limit variable.      
    g_pi_current_array.kp		= INIT_CURRENT_KP;		   // Initialise the current PI proportional gain variable.  
    g_pi_current_array.ki		= INIT_CURRENT_KI;		   // Initialise the current 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_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 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);										   // initialise ADC control reg '0'.
    ADC_CTR2IN = (Y);
    temp = Z;
	#else
    ADC_CTR0 = (X);
    P5DIDIS = (Y);
    ADC_EIC = (Z);
	#endif	//CURRENT_SENSE
    
	#if DAVECG_CURRENT_SENSE
	#if CPU_FREQUENCY <= 20
	#if DAVECG_BTS
    ADC_CTR2	= 0x0000;								   // select the conversion time, sampling time 
														   // and resolution of the ADCs.
    ADC_CTR2IN = 0x0001; 								   // select the Injection mode -conversion time, 
														   // sampling time and resolution of injection 
														   // channels.
	#endif

	#if DAVECG_TLE
    ADC_CTR2 = 0x0000;									   // select the conversion time, sampling time 
														   // and resolution of the ADCs.
    ADC_CTR2IN = 0x0009;								   // select the Injection mode -conversion time, 
														   // sampling time and resolution of injection 
														   // channels. 
	#endif
	#endif	//CPU_FREQUENCY <= 20
	#endif	//CURRENT_SENSE
    
	#if DAVECG_CURRENT_SENSE
	#if REG_BANK_ADC == 1
    SET_FINT_CTRL_REG(ADC_viError, BNKSEL0);			   // configure ADC_viError as Fast Interrupt.
	#endif // REG_BANK_ADC == 1
	#endif // CURRENT_SENSE == 1
}
//*************************************************************************************************
//*************************************************************************************************
// @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.
    CCU6_TCTR4 = 0x4000;
	g_increment_free = 1;								   // set the s/w flag as an acknowledgement to other 
														   // routines that duty cycle has been updated.
#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.
    CCU6_TCTR4 = 0x4000;
	g_increment_free = 1;								   // set the s/w flag as an acknowledgement to other 
														   // routines that duty cycle has been updated.
#endif
}
//*************************************************************************************************
INLINE void GPT1_TMR22_CBLOCK(void)
{
}
//*************************************************************************************************
INLINE void GPT1_TMR25_CBLOCK(void)
{
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void MOTOR_RAMP_GEN(void)     
// Description		This function implements the ramping of motor speed to the new end reference.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void MOTOR_RAMP_GEN(void)
{
	motor_ramp_generation();							   // ramp up the motor speed to the 
														   // new end reference.
}
//*************************************************************************************************
//*************************************************************************************************
// @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, (18*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'.     
    }
}
//*************************************************************************************************
//*************************************************************************************************
// @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	//CURRENT_SENSE					                                                        
		#endif	//BTS							                                                        
		//----------------------------------------                                                      
		#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	//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
		    g_current = ((ADC_DAT2 << 3) & 0x7FFF) - g_adc_offset_res;
			#endif // BTS == 1
			//----------------------------
			#if DAVECG_TLE
		    int l_current_aux = 0;
				#if DAVECG_KEIL
				//------------------------
				_push_(MCW);
				l_current_aux = (ADC_DAT2 << 4) + 0x8000;
				_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
				long l_co_instructions = 0;
				l_co_instructions = (unsigned int)((ADC_DAT2 << 4) + 0x8000);
				_CoLOAD(l_co_instructions << 16);
				_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
				//------------------------
			#endif	//TLE
			#endif	//CURRENT_SENSE
				#if DAVECG_CURRENT_SENSE
				#if DAVECG_BTS
				g_pic_current_out = pi_controller64(&g_pi_current_array.yn, g_pic_speed_out, g_current);
    			g_duty_cycle = PULSE_PERIOD - g_pic_current_out;
				#endif // BTS == 1
				#if DAVECG_TLE
				g_pic_current_out = pi_controller64(&g_pi_current_array.yn, g_pic_speed_out, g_current);
				g_duty_cycle = PULSE_PERIOD - g_pic_current_out;
				#endif // TLE == 1
				#endif	//CURRENT_SENSE
		DUTY_CYC_UPDATE();
		OVR_CURRENT_CHECK();
    	#if DAVECG_TLE
			#if DAVECG_CURRENT_SENSE
			#if DAVECG_KEIL
			MCW = _pop_();
			#endif //	KEIL
			#endif
		#endif // TLE == 1
		    #if DAVECG_CONTROL_PANEL_ENABLE
				trace();
			#endif
}
//*************************************************************************************************
INLINE void CCU6_NODEI3_LOCAL_VAR(void) 
{
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void CCU6_NODEI3_CBLOCK(void)     
// Description		This function regulates the motor speed by calling Pi_controller routine.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void CCU6_NODEI3_CBLOCK(void)
{
    PECC0 = SPEED_CON_TIME;
    if (g_pic_current_out == g_pi_current_array.ymax)
    {
        g_pi_speed_array.ymax = g_pic_speed_out;
    }
    g_pic_speed_out = pi_controller64(&g_pi_speed_array.yn, g_speed_ref, g_speed_CC60);
	g_increment_free = 1;
}
//*************************************************************************************************
#endif // _CTRL_H_
