//////////////////////////////////////////////////////////////////////
//********************************************************************
//********************		CCB Functions		**********************
//********************************************************************
//////////////////////////////////////////////////////////////////////


//****************************************************************************
// @Project Includes
//****************************************************************************
 #include "MAIN.H"
 #include "CONFIG.H"
//****************************************************************************
// @Macros
//****************************************************************************


//****************************************************************************
// @Defines
//****************************************************************************
 
  

//****************************************************************************
// @Typedefs
//****************************************************************************
#if DAVECG_ControlAlgoKBS.SDCC
//****************************************************************************
// @Imported Global Variables
//****************************************************************************
 extern	data at 0x0028		unsigned int  	g_current_ref;
 extern	idata at 0x0092  	unsigned int 	current_kp;
 extern	idata at 0x0094  	unsigned int 	current_ki;

  //control Parameter
 extern 		bit			gb_overcurrent;
 extern 		bit 		gb_hs_error;
 extern 		bit 		gb_ctrap;
 extern 		bit	 		gb_time_out;
 extern 		bit 		gb_On;
 extern 		bit 		gb_Off;

 extern data at 0x0020		unsigned char 	Status_word; 
  
 extern const				unsigned char	g_vector_table_r_l[];
 extern data 				signed int 		pierror;
 extern data  				unsigned int 	g_pi_controller_out;
 extern idata at 0x0088		unsigned int 	g_bemf_check_freq;					   
 extern idata at 0x008A		unsigned int  	g_bemf_end_freq;	
 extern idata at 0x0082		int  			g_freq_increment;	
 extern idata at 0x0084		int 			g_volt_increment;
 extern idata at 0x0086		unsigned int 	g_start_duty_c;
 extern idata at 0x0080		unsigned int 	g_start_freq;
 extern xdata 				int 			task_counter;
 extern data at 0x002E		unsigned int 	g_direction;	
 extern data  at 0x002C		int 			g_current; 
 extern idata at 0x0090		int 			g_speed_CC60;

 #if DAVECG_ControlAlgoKBS.CP_ENABLE
 extern xdata				unsigned char	UART_Tx0[5];
 extern xdata				unsigned char	UART_Tx1[6];
 extern						char			RI_Count;
 extern						bit				bituartRI;
 #endif
 extern bit									bitTimeout;
//****************************************************************************
// @Global Variables
//****************************************************************************
//speed measurement
  xdata		unsigned int 	g_speed_buffer[6*PP];
  xdata		unsigned long 	g_speed_acumm;
  xdata		unsigned char 	g_circ_index;
  xdata		unsigned char 	g_speed_counter;	
  
  data		int  			g_duty_cyc;
  xdata		int	 			g_i_counter;	

 //Bemf Parameter
  xdata		int				l_bemf_aux;
  xdata		int				g_bemf_aux;
  xdata		unsigned char	channel;
  data		unsigned int 	g_back_emf_measure;
  data		unsigned int 	g_v_counter;							   // s/w time base to increment the 'voltage' in BEMF startup mode.
  data		unsigned int 	g_f_counter; 
  data		unsigned char 	g_state;
  data		unsigned char 	g_slope;
  data		unsigned int 	g_time_measure;
  data		unsigned char	g_vector;
  data		unsigned int  	g_angle_inc;
  xdata		long 			g_start_angle;
  data		unsigned int 	g_freq_step;
  data		unsigned int 	g_s_counter0;						   // s/w time base used in 'pre-positioning' stage of commutation.
  data		unsigned int 	g_s_counter1;						   // s/w time base used in 'pre-positioning' stage of commutation.
  data		unsigned int 	g_s_counter2;						   // s/w time base used in 'pre-positioning' stage of commutation.
  data		int 		 	g_adc_mem;
  data		unsigned int 	compare_value;
  xdata		unsigned int 	high_limit;						       // Variable to hold ZCD-Hysteresis upper level.
  xdata		unsigned int 	low_limit;
  xdata		pi_con  		g_pi_array;
#endif

#if DAVECG_ControlAlgoKBS.KEIL
//****************************************************************************
// @Imported Global Variables
//****************************************************************************
  extern	data	unsigned int 	g_current_ref;
  extern	idata	unsigned int 	current_kp;
  extern	idata	unsigned int 	current_ki;

  //control Parameter
  extern 			bit				gb_overcurrent;
  extern 			bit 			gb_hs_error;
  extern 			bit 			gb_ctrap;
  extern 			bit	 			gb_time_out;
  extern 			bit 			gb_On;
  extern 			bit 			gb_Off;

  extern	data 	unsigned char 	Status_word; 

  extern	const	unsigned char	g_vector_table_r_l[];
  extern	data 	signed int 		pierror;
  extern	data  	unsigned int 	g_pi_controller_out;


  extern	idata	unsigned int 	g_bemf_check_freq;					   
  extern	idata 	unsigned int  	g_bemf_end_freq;	
  extern	idata	int  			g_freq_increment;	
  extern	idata	int 			g_volt_increment;
  extern	idata	unsigned int 	g_start_duty_c;
  extern	idata	unsigned int 	g_start_freq;
  extern	xdata 	int 			task_counter;
  extern	data	unsigned int 	g_direction;	
  extern	data	int 			g_current; 
  extern	idata	int 			g_speed_CC60;
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
 extern		xdata	unsigned char	UART_Tx0[5];
 extern		xdata	unsigned char	UART_Tx1[6];
 extern				char			RI_Count;
 extern				bit				bituartRI;
 #endif
extern				bit				bitTimeout;
//****************************************************************************
// @Global Variables
//****************************************************************************
  
  //speed measurement
  xdata		unsigned int 	g_speed_buffer[6*PP];
  xdata		unsigned long 	g_speed_acumm;
  xdata		unsigned char 	g_circ_index;
  xdata		unsigned char 	g_speed_counter;	

  data		int  			g_duty_cyc;
  xdata		int	 			g_i_counter;	
  
  //Bemf Parameter
  
  xdata		int				g_bemf_aux;
  xdata		unsigned char	channel;
  xdata		int				l_bemf_aux;
  idata		unsigned int 	g_back_emf_measure;
  idata		unsigned int 	g_v_counter;							   // s/w time base to increment the 'voltage' in BEMF startup mode.
  idata		unsigned int 	g_f_counter; 
  data		unsigned char 	g_state;
  data		unsigned char 	g_slope;
  xdata		unsigned int 	g_time_measure;
  idata		unsigned int 	g_vector;
  idata		unsigned int  	g_angle_inc;
  idata		long 			g_start_angle;
  idata		unsigned int 	g_freq_step;
  xdata		unsigned int 	g_s_counter0;						   // s/w time base used in 'pre-positioning' stage of commutation.
  xdata		unsigned int 	g_s_counter1;						   // s/w time base used in 'pre-positioning' stage of commutation.
  xdata		unsigned int 	g_s_counter2;						   // s/w time base used in 'pre-positioning' stage of commutation.
  idata		int 		 	g_adc_mem;
  idata		unsigned int 	compare_value;
  xdata		unsigned int 	high_limit;						       // Variable to hold ZCD-Hysteresis upper level.
  xdata		unsigned int 	low_limit;
  xdata		pi_con  		g_pi_array;
#endif
//****************************************************************************
// @External Prototypes
//****************************************************************************
 extern  unsigned int PIControllerCurrent(long *buf_ptr,unsigned int reference,unsigned int act);
//****************************************************************************
// @Prototypes Of Local Functions
//****************************************************************************
  void MotorControl_vInit( void );
  void CPInitVar(void);
  void BEMFParamInit(void);
  void MotorStart(void);
  void ControlInit(void);
  void CommInit(void);
  void MotorStop(void);
  #if DAVECG_SPEED_CALCU
  int  SpeedCalculation();
  #endif
  void OverCurrentCheck(void);
  void Ramp(void);
  void Commutation(void);
  void INIT_PI_VAR(void);
  void Current_CV_Measurement(void);
  void Channel_Select(void);
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  void UARTInitVar(void);
  #endif
//****************************************************************************

void MotorControl_vInit( void )
{
  #if DAVECG_DriveKBS.InvActiveLow
  DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_ON;  										// disable inverter 
  #endif
  #if DAVECG_DriveKBS.InvActiveHigh
  DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_OFF;  										// disable inverter 
  #endif
	CPInitVar();
	BEMFParamInit();
	INIT_PI_VAR();
	#if DAVECG_ControlAlgoKBS.CP_ENABLE
	UARTInitVar();	
	RI_Count=0;
	bituartRI=0;
	#else
	MotorStart();
	#endif
} // End of function MotorControl_vInit();

void CPInitVar(void)
{		
	g_direction		=	MOTOR_DIRECTION * DIRECTION_SCALE;			  
    g_current_ref   =	MOTOR_CURRENT_REF;
	g_speed_CC60	=	0;
	Status_word		=	1;
}

void BEMFParamInit(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;
}

#if DAVECG_ControlAlgoKBS.CP_ENABLE
void UARTInitVar(void)
{
	//statusword /display variable
	#if DAVECG_ControlAlgoKBS.SDCC
	UART_Tx0[0]	= (unsigned char)&Status_word;
    UART_Tx0[1]	= (unsigned char)&g_speed_CC60+1;
   	UART_Tx0[2]	= (unsigned char)&g_speed_CC60;
	UART_Tx0[3]	= (unsigned char)&g_current+1;
	UART_Tx0[4]	= (unsigned char)&g_current;
	#endif
	#if DAVECG_ControlAlgoKBS.KEIL
	UART_Tx0[0]	= (unsigned char)&Status_word;
    UART_Tx0[1]	= (unsigned char)&g_speed_CC60;
   	UART_Tx0[2]	= (unsigned char)&g_speed_CC60+1;
	UART_Tx0[3]	= (unsigned char)&g_current;
	UART_Tx0[4]	= (unsigned char)&g_current+1;
	#endif

    //Graph DATA
	UART_Tx1[0]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar0@;
    UART_Tx1[1]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar1@;
    UART_Tx1[2]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar2@;
   	UART_Tx1[3]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar3@;
	UART_Tx1[4]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar4@;
	UART_Tx1[5]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar5@;
}
#endif

void MotorStart(void)
{
 	Status_word	= 0;  //Reset Ctrap, Timeout, overcurrent, wronghall
 	gb_On		= 1; 
    ControlInit();
	CommInit();
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_OFF;  										// Enable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_ON;  										// Enable inverter 
	#endif
}

 void ControlInit(void) 
{
    int counter = 0;

    for(counter = 0;counter < (6 * PP);counter++)
    {
        g_speed_buffer[counter] = 0;
    }

    g_speed_acumm    = 0x00000008;						   
														   
    g_circ_index    = 0x0000;                   
    g_speed_CC60    = 0x0000;
    g_speed_counter = 0x0000;
	g_duty_cyc		=  BEMF_CONST_1 - g_start_duty_c;                    
    

//bemf commutation fn() variables

    g_back_emf_measure	= 0x0000;						   	
    g_v_counter			= 0x0000;							                                                                                                                   
    g_f_counter			= 0x0000;							                                                                                                                   
    g_state				= 0x0000;							   
    g_slope				= 0x0000;							   
	g_time_measure		= 0x0000;						// Reset the variable which holds the measured 'time between two zero crossings' to zero.
    g_vector			= 0x0000;
    g_angle_inc			= g_start_freq + 2;				// Initialize the ramp-up Angle Increment variable to be slightly greater than Start Frequency.                    
    g_start_angle		= COMMUTATION_ANGLE - 0x0200;	// Initialize the ramp-up Start Angle to be slightly lesser than Commutation Angle.      
    g_freq_step			= 0x0000;
    g_s_counter0		= DELAY_COMMUT_0;                         
    g_s_counter1		= 0x0000;
    g_s_counter2		= 0x0000;
	task_counter		= 0;
	g_i_counter			= 0;							//overcurrent measurement counter
	bitTimeout			= 0;
 	SFR_PAGE(_cc0, noSST);								// switch to page0
 	CCU6_CC63SRLH		= PULSE_PERIOD;//	0x850;
 	CCU6_TCTR4H			= 0x40;
 	g_pi_array.intg_buffer = 0;
} 

void CommInit(void)
{
	SFR_PAGE(_cc2, noSST);         						   // switch to page 0
    CCU6_MCMCTR			=	0x0014;						   // Trigger Shadow Tranfers at correct hall
	CCU6_TRPCTRH		|=	0x80;

	SFR_PAGE(_cc0, noSST);         						   // switch to page 0
	CCU6_MCMOUTSL		=	0x0024 | 0x80;
    CCU6_TCTR4H			=   0x06;						   // T13 Reset/Run --> Start PWM 
	CCU6_TCTR4L			=   0x00;   

}

void MotorStop(void)
{
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_ON;  										// disable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_OFF;  										// disable inverter 
	#endif
	TR2				= 1; //   start timer

	SFR_PAGE(_cc2, noSST);         						   // switch to page 0
    CCU6_MCMCTR		= 0x0000;                              // CCU6 multi channel mode control        
                                                           // Enable Shadow Tranfers direct mode
    SFR_PAGE(_cc0, noSST);         						   // switch to page 0
    CCU6_MCMOUTSL	= 0x80;                                // All Transistors OFF
	CCU6_MCMOUTSH	= 0x80;
	CCU6_TCTR4L		= 0x05;                                 // CCU6 timer control register 4
    CCU6_TCTR4H		= 0x05;                                 // T13/T12 Reset, T13/T12 Stop -->  No PWM active 
	CCU6_CC63SRL		= PULSE_PERIOD;                         // Re-initialise shadow register channel 3 with 'PULSE_PERIOD'
	CCU6_CC63SRH	= PULSE_PERIOD>>8; 													   // so that it is ready with the correct value when 'motor start'
														    // command is issued.														
                                    
    CCU6_TCTR4L		= 0x00;									 // CCU6 timer control register 4 
    CCU6_TCTR4H		= 0x40;                                  // Shadow Tranfers by T13 Zero-Match    
        
    gb_Off			= 1;
 	gb_On			= 0; 
	g_current		= 0;
	g_speed_CC60	= 0;
	g_speed_counter = 0;	
 }
 
 #if DAVECG_ControlAlgoKBS.SPEED_CALCU
 int SpeedCalculation()   
 {
	static unsigned int  l_time;
    unsigned long	l_speed_cal ;
	
	g_speed_acumm  += g_time_measure;					   // Accumulate the new sample i.e measured time
														   // into a Moving Average Accumulator.
    g_speed_acumm  -= g_speed_buffer[g_circ_index];		   // Subtract out the oldest sample from the Accumulator.       

    g_speed_buffer[g_circ_index] = g_time_measure;       // Preserve the latest sample so that it can be subtracted
														   // out when required.
    g_circ_index++;       
    if(g_circ_index > INDEX_LIMIT)						   // end of circular buffer reached ?
    {
        g_circ_index = 0;  
        if((int)((long)g_speed_acumm >> 16)  > 0)		   // accumulated time too big a number?.i.e motor speed too high?
        {
		    l_time = g_speed_acumm >> (SPEED_TIME_DIV);    // then scale it down to a smaller number.
		    l_speed_cal = SPEED_CONSTANT_AV;               // Load the division factor to calculate motor speed.  
        }
		else
		{												   // so accumulated time not a big number...i.e motor speed not that high.....
		    l_time = g_speed_acumm;                        // hence do not scale it down so that no precision loss.
		    l_speed_cal = SPEED_CONSTANT_AV_FACTOR;        // Load the division factor to calculate motor speed.  
		}
			
		l_time= l_speed_cal / l_time;
    }
	if(g_speed_counter < PP_FACTOR)							// motor still in ramp up stage?
    {
      	 g_speed_counter = g_speed_counter + 1;		   		// then Moving Average Accumulator still hasn't sufficient samples.
         l_time=0;      
    } 

	return (l_time);										// finally compute motor speed.
}
#endif

void OverCurrentCheck(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 ?
        {
			 gb_overcurrent = 1;						   
		     MotorStop();								   
        }
    }
    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 ramp(void)
// Description		This function implements the ramping-up of the motor speed
//					during the start-up stage of the motor.
//----------------------------------------------------------------------------
void Ramp(void) 
{
    if(g_angle_inc < g_bemf_end_freq)							// Maximal frequency
	{                                            
        if(g_state == 1)
        {
            g_v_counter++;										// Increment the s/w time base which determines the rate of dutycycle increment.
            g_f_counter++;										// Increment the s/w time base which determines the rate of modulation pattern update.
             
            if(g_f_counter > g_freq_increment)					// Time to increment angle ?
 			{                                           
				#if DAVECG_ControlAlgoKBS.START_RAMP
                g_angle_inc+=1; 							// then increment angle....( for LINEAR ramp).
				#else
                g_freq_step++;                        
                g_angle_inc  += g_freq_step >> 4;			// then increment angle....( for QUAD ramp).
				#endif	// START_RAMP
				g_f_counter = 0;							// and reset the time base of angle increment.                                                       
            }
            if(g_v_counter > g_volt_increment)					// Time to increment dutycycle ?                                    
 			{                                                                                           
				 g_duty_cyc--;									// then increment dutycycle.                                           
				
				 g_v_counter = 0;								// and reset the time base of dutycycle increment.
			
				if (g_duty_cyc < START_DUTY_CYCLE_MIN) 					   
					g_duty_cyc	= START_DUTY_CYCLE_MIN;					
				SFR_PAGE(_cc0, noSST);								// switch to page0
				CCU6_CC63SRLH	=	g_duty_cyc;
		    	CCU6_TCTR4H  = 0x40;								// Shadow Tranfers T13 enable    
            }
        }
    }
    g_start_angle += g_angle_inc;								// Increment angle
    if(g_start_angle > COMMUTATION_ANGLE)						// Time to output the next modulation pattern ? 
	{
        g_start_angle = 0;										// then reset the time base of angle increment
		//----rampup--------------------------
		SFR_PAGE(_cc0, noSST);         						// switch to page 0
		CCU6_MCMOUTSL	=	g_vector_table_r_l[g_vector + g_direction] | 0x80;
		g_vector++;                                         // Modulation pattern update and                                                                                                                
		                                                     // Increment modulation pattern index      
		if(g_vector > 5)									// End of modulation table reached ?
		{
			g_vector = 0;									// then reset it to '0'.
		}
	} 
}

//****************************************************************************
// @Function        void commutation(void)
// Description		This function implements the following:
//					0.	Pre-Positioning of the Motor if required.
//					1.	Ramping-up of the motor during start up phase.
//					2.	Verification of Back EMF build up through Zero 
//						Crossing detection and.....
//					3.	Maintaining of steady state operation of the Motor.
//----------------------------------------------------------------------------
void Commutation(void)      
{
	switch(g_state) 
    {
    	case 0:																   // here the motor coils are energized in a pre-defined pattern,                                                
        {																	   // so that the rotor 'jerks' and locks into a proper position.
        	#if  DAVECG_ControlAlgoKBS.ENABLE_PREPOSITIONING
			 if(g_s_counter2 > g_s_counter0)								   // required delay elapsed ?
                {
                      g_s_counter1++;										   // then increment the next level of delay counter.
                      g_s_counter2 = 0;
                }
                SFR_PAGE(_cc0, noSST);                   
                if(g_s_counter1 == 1)										   // time to output the next modulation pattern.
                {               
                     g_s_counter1++;        
                     CCU6_MCMOUTSL = g_vector_table_r_l[ 1 + g_direction]| 0x0080;
                }                                                              // if yes read the zero'th modulation pattern from table and output.....         
																			   // ....it to MCMOUT register.
                if(g_s_counter1 == 3)										   // time to output next modulation pattern.
                {                                                              
                     g_s_counter1++;                                                                    
                     CCU6_MCMOUTSL = g_vector_table_r_l[ 2 + g_direction]| 0x0080;
                }                                                              // if yes read the second modulation pattern from table and output ......
																			   // ..... it to MCMOUT register.
               if(g_s_counter1 == 5)										   // required delay over ?
                {                                                                        
                     g_s_counter1++; 
                     if(g_direction==0)											// direction selected is 'clockwise' 
                      	CCU6_MCMOUTSL = 0x26| 0x0080;							// then energize appropriate coil by sending out the corresponding modulation pattern.
                     else														// otherwise if direction selected is 'counter-clockwise'....
                     	CCU6_MCMOUTSL = 0x29| 0x0080;						   	// then energize appropriate coil by sending out the corresponding modulation pattern.
                     	
                     g_duty_cyc   = BEMF_CONST_2 - g_start_duty_c;			   // calculate duty cycle required for next state.                 
                     g_s_counter0 = DELAY_COMMUT_1;							   // initialize the software time base required for next state.            
                }                                                         
                                       
                if(g_s_counter1 == 7)										   // if we have reached the end of present state....
                {															   // then initialize the variables as required for next state.....
					 g_duty_cyc   = PULSE_PERIOD - g_start_duty_c;			   // Initialise Duty_cycle with user value.                  
					 g_s_counter0 = 0;										   // reset all the software timebases to '0'.
                     g_s_counter1 = 0;
                     g_s_counter2 = 0;
                     g_state	  = 1;										   // make state = '1'. i.e exit state '0'.
                     g_vector	  = 3;										   // since we have already sent two modulation patterns, let the table pointer point to the 3rd pattern.
                     CCU6_CC62SRLH = 0xFFFF;								   // Load maximum value into CCU6 channel2 register. i.e let the time-out period be maximum to begin with.                            
                     CCU6_TCTR4L  = 0x40;									   // reset timer T12.
                     CCU6_TCTR4H  = 0x00;									   // reset timer T12.
				}

                if(g_s_counter1 > 7)										   // if the variable has taken an 'abnormal' value......
                {
                     g_state = 4;											   // ....then go to state '4' and stop motor.
                }

                g_s_counter2++;
				 if(g_duty_cyc < DUTY_CYCLE_MIN)
						g_duty_cyc = DUTY_CYCLE_MIN;
				else if(g_duty_cyc > DUTY_CYCLE_MAX)
					g_duty_cyc = DUTY_CYCLE_MAX;
	
				SFR_PAGE(_cc0, noSST);										// switch to page 0
				CCU6_CC63SRLH = g_duty_cyc;									// ....load it into the PWM duty cycle reg.
				CCU6_TCTR4H = 0x40;	
				CCU6_TCTR4L = 0x00;	


            #else // ENABLE_POSITIONING == 1
            g_duty_cyc   = PULSE_PERIOD - g_start_duty_c;				   // Initialise Duty_cycle with user value.                  
            g_s_counter0 = 0;											   // reset all the software timebases to '0'.
            g_s_counter1 = 0;
            g_s_counter2 = 0;
            g_state  = 1;												   // make state = '1'. i.e exit state '0'.
            g_vector = 0;											       // since we have already sent two modulation patterns, let the table pointer point to the 3rd pattern.         
			SFR_PAGE(_cc0, noSST);         		  					   // switch to page 0
                 
			CCU6_CC62SRLH = 0xFFFF;									   // Load maximum value into CCU6 channel2 register. i.e let the time-out period be maximum to begin with.                                                        
            CCU6_TCTR4L  = 0x40;										   // Run timer T12
			CCU6_TCTR4H  = 0x00;
			#endif
			break;
        }
       // FREQUENCY RAMP  ***************************************
        // Back-emf checking  
        case 1: 
        {          												  
            if(g_s_counter2 > DELAY_TIME_OUT)								   // Time out duration elapsed?    
            {
                 g_state = 4;												   // then go to state4 and stop motor.
            }      
            if(g_angle_inc > g_bemf_check_freq)								   // BEMF check freq still not reached?         
			{                                  
            	g_s_counter2++; 
				SFR_PAGE(_ad2, noSST);
				g_adc_mem	=	(ADC_RESR3L >> 6)&0x0003;
				g_adc_mem	=	g_adc_mem | (((uword)ADC_RESR3H << 2));
			
				g_back_emf_measure  = (g_adc_mem & 0x03FF);					   // read BEMF signal.
                
                if(g_slope == 0)											   // Are we looking for rising edge ?
              	{                    
                	if(g_back_emf_measure > high_limit)					   // then see whether BEMF signal is greater than Specified limit.
                    {													   
                    	g_s_counter1++;								   // If yes increment the samples(filter) time base.
                        if(g_s_counter1 == 10)							   // 10 consecutive valid BEMF samples detected? 
                        {
                        	g_slope = 1;								   //  then make slope='1',so that next we look for falling edge.
                            g_s_counter0++;
                            g_s_counter1 = 0;
                    	}    
                   	}
             	}  
                if(g_slope == 1)											   // Are we looking for falling edge ?
                {
                	if(g_back_emf_measure < low_limit)					   // then see whether BEMF signal is less than specified limit.
                    {                                   
                    	g_s_counter1++;								   // If yes increment the samples(filter) time base.
                        if(g_s_counter1 == 10)							   // 10 consecutive valid BEMF samples detected? 
                        {
                        	g_slope = 0;								   //  then make slope='0',so that next we look for rising edge.
                            g_s_counter0++;
                            g_s_counter1 = 0;
                        }   
                  	}
                }        
                if(g_s_counter0 == 2)										   // Both rising edge & falling edge successfully detected ?
               	{
                	g_s_counter1 = 0;
                    g_s_counter2 = 0;
                    g_state = 2;											   // then make state = 2 so that we ramp up the motor even further.
				}                                
				 
            }                     
            break;
        }
                                     
        case 2:
        {   
            if(g_s_counter2 > DELAY_TIME_OUT)								   // Time_out duration elapsed ?
            {
                 g_state = 4;												   // then go to state4 and stop motor.
            }       
			g_s_counter2++;
			SFR_PAGE(_ad2, noSST);
			g_adc_mem	=	(ADC_RESR3L >> 6)&0x0003;
			g_adc_mem	=	g_adc_mem | (((uword)ADC_RESR3H << 2));
			g_back_emf_measure = (g_adc_mem & 0x03FF);						   // read BEMF signal.
            
            if(g_slope == 0)												   // Are we looking for rising edge ?
            {     
            	if(g_back_emf_measure >= (compare_value + DELTA))		   // then see whether BEMF signal is greater than half of bus voltage.
                {    
                	g_s_counter1++;										   // if yes, increment samples counter (filter time base).
                    if(g_s_counter1 == 4)								   // 10 consecutive valid BEMF samples detected? 
                    {
                        g_slope = 1;									   // then make slope = '1', so that next we look for falling edge.
						SFR_PAGE(_cc3, noSST);         		  		   // switch to page 0
                        g_time_measure = CCU6_T12LH;					   // Save the captured time between two BEMF zero crossings. 
			 			SFR_PAGE(_cc0, noSST);         		  	       // switch to page 0
                        CCU6_TCTR4L  = 0x06;							   // T12 Reset and re-start.
                        CCU6_TCTR4H  = 0x00; 
						g_s_counter1 = 0;
                  	}
            	}
            }   
            
            if(g_slope == 1)												   // time to look for falling edge ?
            {                                   
            	if(g_back_emf_measure <(compare_value - DELTA))		   // then see whether BEMF signal is less than half of bus voltage.
                {  
                	g_s_counter1++;										   // if yes, increment samples counter (filter time base).
                    if(g_s_counter1 == 4)								   // 10 consecutive valid BEMF samples detected? 
                    {
                    	g_slope = 0;                                       // then make slope = '0', so that next we look for rising edge.
						SFR_PAGE(_cc3, noSST);         		  		   // switch to page 0
                        g_time_measure = CCU6_T12LH;					   // Save the captured time between two BEMF zero crossings. 
			 			SFR_PAGE(_cc0, noSST);         		  		   // switch to page 0
                        CCU6_TCTR4L  = 0x06;							   // T12 Reset and re-start.                        
                        CCU6_TCTR4H  = 0x00;
						g_s_counter1 = 0;
               		} 
             	}
            }                                               
          	if(g_time_measure > 0)											   // sufficient motor speed achieved ? 
            {	
            	SFR_PAGE(_cc0, noSST);         		  					   // switch to page 0
                CCU6_CC61SRLH = (g_time_measure >> 1) - (DELTA + DELAY);      // Initialise CCU6 channel1 with present motor speed.
                CCU6_CC62SRLH = CCU6_CC61SRLH + (CCU6_CC61SRLH >> 2);         // Initialise CCU6 channel2 with with sufficiently higher value to implement time out.
                CCU6_TCTR4L  = 0x45;                                          // T12 Reset and Stop (updated CC61R).
				CCU6_TCTR4L  = 0x02;                                          // T12 Run.
				CCU6_MCMOUTSL = g_vector_table_r_l[g_vector + g_direction];   // Update MCMOUTS register with next modulation pattern.
                g_vector++;                                                   // Increment modulation pattern index.
                if(g_vector > 5)											   // Index has reached the limit (6) ?
                {
                	g_vector = 0;										   // then reset it to '0'.
               	}                                     
                g_slope = g_slope + 2;										   // remember the present slope so that we know whether to look for rising or falling edge in state 3.                          
                CCU6_TCTR4H  = 0x40;
				TR2 = 0; 
                g_state = 3;      
				task_counter=0;    
          	}  
          	break;
        }
             
        // COMMUTATION WITH BACK-EMF MEASUREMENT ***************************************
        // Continuous operation
        case 3:																   // Enter state 3 ---- steady state operation.
        {
  			SFR_PAGE(_ad2, noSST);
			g_adc_mem	=	(ADC_RESR3L >> 6)&0x0003;
			g_adc_mem	=	g_adc_mem | (((uword)ADC_RESR3H << 2));
							
			g_back_emf_measure  = (g_adc_mem & 0x03FF);  

			if(g_slope == 0)												   // Are we looking for rising edge ?
            {    
			    if(g_back_emf_measure >= (compare_value))					   // and see whether the BEMF voltage is greater than half of Bus voltage.
				{																   // i.e we are looking whether valid zero crossing detected.         
                	g_s_counter1++;										   // if yes increment the sample counter (for filtering purpose).									                                       
                    if(g_s_counter1 == 2)								   // Two consecutive valid samples detected ?
                   	{													   // then let us make arrangements for falling edge detection.												
                    	g_s_counter1 = 3;							   // reset sample counter.
                        g_slope = 3;								   // make slope = 3, so that next we start looking for falling edge.
                  	} 
              	}
         	}                                                                   
            else if(g_slope == 1)											   // Are we looking for falling edge ?
           	{     
                                                                            
            	if(g_back_emf_measure < (compare_value))                   // and see whether the BEMF voltage is less than half of Bus voltage.
				{														   // i.e we are looking whether valid zero crossing detected.
                	g_s_counter1++;                                     // if yes increment the sample counter (for filtering purpose).                                       
                    if(g_s_counter1 == 2)								   // Two consecutive valid samples detected ?
                   	{													   // then let us make arrangements for falling edge detection.												
                    	g_s_counter1 = 3;							   // reset sample counter.
                        g_slope = 2;								   // make slope = 3, so that next we start looking for falling edge.
               		}
				}
					
         	}
			if(g_s_counter1==3)
			{
				g_s_counter1=0;
				SFR_PAGE(_cc3, noSST);         		  		   // switch to page 0
                g_time_measure = CCU6_T12LH;				   // save the captured time between two zero crossings.
				
				SFR_PAGE(_cc0, noSST);         		  		   // switch to page 0
               	CCU6_CC61SRLH = (g_time_measure >> 1) - DELAY; // Initialize the CCU6 channel 1 register with the present motor speed value,
																			   // so that it generates interrupt for every zero crossing.
                CCU6_CC62SRLH  = CCU6_CC61SRLH +5;
                       	 	
                CCU6_TCTR4L   = 0x45;						   // Timer T12 reset and stop.
				CCU6_TCTR4L  = 0x02;                          // T12 re-start.                                
                                
				CCU6_MCMOUTSL = g_vector_table_r_l[g_vector + g_direction];  
				bitTimeout			= 0;       
				g_vector++;                                    // Increment modulation pattern index.
                if(g_vector > 5)							   // index has reached the limit ?
                {
					g_vector = 0;								   // then reset it back to '0'.
               	}
					
         	}
            break;

       	}

            //// TIMEOUT STATE ( SWITCH-OFF) ***************************************
            
        case 4:															   // this state is executed if a time-out has been detected.
        {
			MotorStop();												   // execute motor stop function.
        									   // set the flag to convey to the user that motor has been stopped.
            gb_time_out = 1;											   // set the flag to convey to the user that time out condition has been detected.
            break;
       	}

        default:
        {
            MotorStop();    
            gb_time_out = 1;            
            break;
         }
  	}

} 
void INIT_PI_VAR(void) 
{
    g_pi_array.ymax  = PIC_CURRENT_YMAX;						   // Initialise the PI upper limit variable. 
    g_pi_array.ymin  = PIC_CURRENT_YMIN;						   // Initialise the PI lower limit variable. 
    current_kp    = INIT_CURRENT_KP;					   // Initialise the PI proportional gain variable. 
    current_ki    = INIT_CURRENT_KI;					   // Initialise the PI integral gain variable. 
}

void Channel_Select(void)  
{	  
	SFR_PAGE(_cc3, noSST);         		  		
	l_bemf_aux = (CCU6_MCMOUTL & 0x3F);									// 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...
	
		if((g_bemf_aux == BEMF_AUX_VAL11) || (g_bemf_aux == BEMF_AUX_VAL12)) 
		{																// if phase '1' is Inactive....
			SFR_PAGE(_ad6, noSST);										// switch to page 6
			ADC_CRCR1 = 0x80;											// write channel information to be converted
			ADC_CRMR1 |= 0x40; 											// generate load event	
		} 
		if((g_bemf_aux == BEMF_AUX_VAL21) || (g_bemf_aux == BEMF_AUX_VAL22)) 
		{																// if phase '2' is Inactive.... 
			SFR_PAGE(_ad6, noSST);										// switch to page 6
			ADC_CRCR1 = 0x40;											// write channel information to be converted
			ADC_CRMR1 |= 0x40; 											// generate load event
		} 
		if((g_bemf_aux == BEMF_AUX_VAL31) || (g_bemf_aux == BEMF_AUX_VAL32)) 
		{																// if phase '3' is Inactive.... 
			SFR_PAGE(_ad6, noSST);		 								// switch to page 6
			ADC_CRCR1 = 0x20;											// write channel information to be converted
			ADC_CRMR1 |= 0x40; 											// generate load event
		}
	}

}

void Current_CV_Measurement(void)
{
	SFR_PAGE(_ad0, noSST);
	if((ADC_GLOBSTR & 0x01)==0x00)										// if ADC is not busy.....
	{ 
		SFR_PAGE(_ad2, noSST);											// switch to page 2
		if(ADC_RESR0L & 0x10)											// check whether the result is valid
		{
			ADC_PAGE = 0x02;												// switch to page 2
			channel	=	ADC_RESR0L & 0x07;									// read channel information 
			ADC_PAGE = 0x06;												// switch to page 6
			if (channel == 1)		
			{
				ADC_QINR0 = 0x04;	
				ADC_PAGE = 0x02;										// switch to page 2
				compare_value = (ADC_RESR0L >> 6) & 0x0003;				// read ADC result
				compare_value = compare_value | (((uword)ADC_RESR0H << 2));		// read ADC result
				compare_value = compare_value>>1;
				high_limit		=	compare_value + (compare_value >> 4);
				low_limit		=	compare_value - (compare_value >> 4);
			}	
			else if(channel == 4)
			{
				ADC_QINR0	=	0x01;									// write channel information to be converted
				ADC_PAGE = 0x02;
				g_current = (((((uword)ADC_RESR0H << 2)|(ADC_RESR0L>>6))<<3) & 0x7fff);		// read ADC result
				OverCurrentCheck();
			} 
			else
				ADC_QINR0	=	0x04;									// write channel information to be converted
		}	
	}
}

