//////////////////////////////////////////////////////////////////////
//********************************************************************
//******************	BC SCCB Functions		**********************
//********************************************************************
//////////////////////////////////////////////////////////////////////


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


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

//****************************************************************************
// @Typedefs
//****************************************************************************

//****************************************************************************
// @Imported Global Variables
//****************************************************************************
   //control Parameter
  extern  	C_BDATA			Status_word; 
  extern 	bit				gb_overcurrent;
  extern 	bit 			gb_Closeloop ;
  extern 	bit 			gb_ctrap;
  extern 	bit	 			gb_time_out;
  extern 	bit 			gb_On;
  extern 	bit 			gb_Off;
  extern 	bit 			gb_Ramp;
  extern    const ubyte		g_vector_table_r_l[];
  #if DAVECG_ControlAlgoKBS.KEIL
  extern  cSCCB	C_SDATA		cSCCB0; 
  #endif //End of Keil
  #if DAVECG_ControlAlgoKBS.Tasking
  extern  cSCCB			cSCCB0; 
  #endif //End of TASKING
  
  //****************************************************************************
// @Global Variables
//****************************************************************************
  bit 					bitNewCMD0=0;
  bit					bitTimeout;
  sword		C_SDATA		g_bemf_aux;
  uword		C_SDATA 	Channel_N;
  sword 	C_SDATA		Ramp_Scheduler;
  uword 	C_SDATA		g_speed_buffer[6*PP];
  ulong 	C_SDATA		g_speed_acumm;
  ubyte 	C_SDATA		g_circ_index;
  uword  	C_SDATA		g_speed_CC60;
  ubyte 	C_SDATA		g_speed_counter;	
  sword	 	C_SDATA		g_i_counter;	
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  uword 	C_SDATA		CANTrxBuf0[4];
  uword 	C_SDATA		CANTrxBuf1[4];
  #endif
  //Bemf Parameter
  
  uword 	C_SDATA		g_back_emf_measure;
  uword 	C_SDATA		g_v_counter;							   // s/w time base to increment the 'voltage' in BEMF startup mode.
  uword 	C_SDATA		g_f_counter; 
  uword 	C_SDATA		g_state;
  uword 	C_SDATA		g_slope;
  uword 	C_SDATA		g_time_measure;
  uword 	C_SDATA		g_vector;
  uword 	C_SDATA 	g_angle_inc;
  slong 	C_SDATA		g_start_angle;
  uword 	C_SDATA		g_freq_step;
  uword 	C_SDATA		g_s_counter0;						   // s/w time base used in 'pre-positioning' stage of commutation.
  uword 	C_SDATA		g_s_counter1;						   // s/w time base used in 'pre-positioning' stage of commutation.
  uword 	C_SDATA		g_s_counter2;						   // s/w time base used in 'pre-positioning' stage of commutation.
  sword 	C_SDATA	 	g_adc_mem;
  uword 	C_SDATA		compare_value;
  uword 	C_SDATA		high_limit;						       // Variable to hold ZCD-Hysteresis upper level.
  uword 	C_SDATA		low_limit;
  ulong		C_SDATA		speed_buf;
  
//****************************************************************************
// @External Prototypes
//****************************************************************************
 #if DAVECG_ControlAlgoKBS.CP_ENABLE
 extern void CAN_Transmit_MO1(void);
 #endif
 #if DAVECG_ControlPanelKBS.POT_ENABLE
 extern unsigned int MUL_MAC(unsigned int a, unsigned int b);
 #endif
//****************************************************************************
// @Prototypes Of Local Functions
//****************************************************************************
  void MotorControl_vInit(void );
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  void CANInitVar(void);
  #endif
  void  CPInitVar(void);
  void BEMFParamInit(void);
  void MotorStart(void);
  void ControlInit(void);
  void CommInit(void);
  void MotorStop(void);
  void Ramp(void);
  void Commutation(void);
  int SpeedCalculation(void);
  void PIInitVar(void);
  #if DAVECG_ControlPanelKBS.POT_ENABLE
  void Read_Speed(void);
  #endif
//****************************************************************************
#if DAVECG_ControlAlgoKBS.CP_ENABLE
void CANInitVar(void)
{
  // Status Word, Speed data
  CANTrxBuf0[0] = (unsigned int) &Status_word;					
  CANTrxBuf0[1] = (unsigned int) &cSCCB0.Motor_Current;					
  CANTrxBuf0[2] = (unsigned int) &cSCCB0.Motor_Speed;;					
  CANTrxBuf0[3] = (unsigned int) &cSCCB0.Motor_Current;
 
  // Graph Data
  CANTrxBuf1[0] = (unsigned int) &DAVECG_ControlAlgoKBS.CANMsgVar0@;					
  CANTrxBuf1[1] = (unsigned int) &DAVECG_ControlAlgoKBS.CANMsgVar1@;					
  CANTrxBuf1[2] = (unsigned int) &DAVECG_ControlAlgoKBS.CANMsgVar2@;					
  CANTrxBuf1[3] = (unsigned int) &cSCCB0.Motor_Speed;
  bitNewCMD0 	= 0;
}
#endif
void CPInitVar(void)
{		
	cSCCB0.Speed_End_Ref	= MOTOR_END_REF;					   
	cSCCB0.Speed_Start_Ref	= MOTOR_START_REF;				  
	cSCCB0.Motor_Direction	= MOTOR_DIRECTION * DIRECTION_SCALE;			  
	cSCCB0.Speed_Ref   		= 0;
	cSCCB0.Rampup_Counter 	= SPEED_RAMPUP_COUNT;
	cSCCB0.Motor_Speed		= 0;
	Status_word				= 1;  				
}
void BEMFParamInit(void)
{
	cSCCB0.Bemf_Check_Freq  = BEMF_CHECK_FREQ;				   // initialise 'bemf check freq' with GUI(user) value.       
	cSCCB0.Bemf_End_Freq    = END_FREQUENCY;	 				   // initialise 'bemf end freq' with GUI(user) value.         
	cSCCB0.Freq_Increment   = FREQ_INC;		 				   // initialise 'bemf freq increment' with GUI(user) value.   
	cSCCB0.Volt_Increment   = VOLT_INC;		 				   // initialise 'bemf volt increment' with GUI(user) value.  
	cSCCB0.Start_Duty_Cyc   = START_DUTY_CYC; 				   // initialise 'bemf start duty cycle' with GUI(user) value. 
	cSCCB0.Start_Freq       = START_FREQ;  
}

void MotorControl_vInit( void )
{
  #if DAVECG_DriveKBS.InvActiveLow
  DAVECG_DriveKBS.InvPortPin@ = ENABLE_ON;  										// disable inverter 
  #endif
  #if DAVECG_DriveKBS.InvActiveHigh
  DAVECG_DriveKBS.InvPortPin@ = ENABLE_OFF;  										// disable inverter 
  #endif	
  CPInitVar();
  BEMFParamInit();
  PIInitVar();
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  CANInitVar();
  CAN_Transmit_MO1();
  #else
  MotorStart();
  #endif
} // End of function MotorControl_vInit();

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;

	cSCCB0.Duty_Cyc     	=  BEMF_CONST_1 - cSCCB0.Start_Duty_Cyc;                   
    
   //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      	= cSCCB0.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;
	g_i_counter			= 0;									//overcurrent measurement counter

  	CCU60_CC63SR 		= PULSE_PERIOD;
 	CCU60_TCTR4  		= 0x4040;

 	Ramp_Scheduler		= 1;
	cSCCB0.Motor_Speed	= 0;
	speed_buf			= 0;

	cSCCB0.Speed.Ibuf	= 0;
} 

void CommInit(void)
{
    CCU60_MCMCTR  	= 0x0014;								   // Trigger Shadow Tranfers at correct hall
	CCU60_TRPCTR	|= 0x8000;
	
	CCU60_MCMOUTS	= 0x0024 | 0x80;
	CCU60_TCTR4  	= 0x0600;								   // T13 Reset/Run --> Start PWM 
 }


void MotorStart(void)
{
 	Status_word		= 0;										//Reset Ctrap, Timeout, overcurrent, wronghall
 	gb_On   		= 1; 
    bitTimeout		= 0;                        

	if(cSCCB0.Speed_Start_Ref > cSCCB0.Speed_End_Ref)                  
    {
    	cSCCB0.Speed_Start_Ref = cSCCB0.Speed_End_Ref;				// Ensure that 'start_ref' never exceeds 'end_ref'.
    }        
    cSCCB0.Speed_Ref	= cSCCB0.Speed_Start_Ref;
	
	ControlInit();
	CommInit();
	 #if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.InvPortPin@ = ENABLE_OFF;  										// enable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.InvPortPin@ = ENABLE_ON;  										// enable inverter 
	#endif
	#if DAVECG_ControlAlgoKBS.CP_ENABLE
	CAN_Transmit_MO1();
	#endif
}
 
void MotorStop(void)
{
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.InvPortPin@ = ENABLE_ON;  										// disable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.InvPortPin@ = ENABLE_OFF;  										// disable inverter 
	#endif
	gb_Ramp				= 0;
   	CCU60_MCMCTR 		= 0x0000;							// CCU6 multi channel mode control        
															// Enable Shadow Tranfers direct mode
   	CCU60_MCMOUTS 		= 0x8080;							// All Transistors OFF
	CCU60_TCTR4 		= 0x0505;							// CCU6 timer control register 4
   															// T13/T12 Reset, T13/T12 Stop -->  No PWM active 
    CCU60_CC63SR 		= PULSE_PERIOD;						// Re-initialise shadow register channel 3 with 'PULSE_PERIOD'
															// so that it is ready with the correct value when 'motor start'
															// command is issued.														
    CCU60_TCTR4 		= 0x4000;							// CCU6 timer control register 4 
    														// Shadow Tranfers by T13 Zero-Match    
 	gb_Off				= 1;
 	gb_On   			= 0; 
	gb_Closeloop		= 0;

	cSCCB0.Motor_Current	= 0;
	g_speed_CC60		= 0;
	g_speed_counter		= 0;	
	cSCCB0.Speed_Ref   	= 0;
	cSCCB0.Motor_Speed	= 0;
	speed_buf			= 0;
	#if DAVECG_ControlAlgoKBS.CP_ENABLE
	CAN_Transmit_MO1();
	#endif
 }

int SpeedCalculation()   
{
    unsigned int  l_time ;
    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.
    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 			= g_time_measure;					// Hence use the present sample directly, instead of moving average filter. 
        l_speed_cal 	= SPEED_CONSTANT ;					// Load constant value in l_speed_cal.  
    }                                                      
    else													// if motor has passed ramp up stage....
    {														// then the accumulator has sufficient samples.
        if((int)((long)g_speed_acumm >> 16)  > 0)			// accumulated time too big a number?.i.e motor speed too high?
        {
		    l_time 		= (int)(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 		= (int)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.  
		}
    }
	g_circ_index++;
															// Increment index for circular buffer
    if(g_circ_index > INDEX_LIMIT)							// end of circular buffer reached ?
    {
        g_circ_index = 0;									// then reset the Index of the buffer to '0'.
    }
	return (l_speed_cal / l_time);							// finally compute motor speed.
}

//****************************************************************************
// @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 < cSCCB0.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 > cSCCB0.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 > cSCCB0.Volt_Increment)				// Time to increment dutycycle ?                                    
 			{                                                                                           
				cSCCB0.Duty_Cyc--;								// then increment dutycycle.                                           
				g_v_counter 	= 0;							// and reset the time base of dutycycle increment.
				if (cSCCB0.Duty_Cyc < START_DUTY_CYCLE_MIN) 					   
					cSCCB0.Duty_Cyc	= START_DUTY_CYCLE_MIN;					
				CCU60_CC63SR	= cSCCB0.Duty_Cyc;
		    	CCU60_TCTR4   	= 0x4040;						// 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
		CCU60_MCMOUTS	= g_vector_table_r_l[g_vector + cSCCB0.Motor_Direction] | 0x0080;
		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 
//					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;
            }
            if(g_s_counter1 == 1)											// time to output the next modulation pattern.
            {               
				g_s_counter1++;        
                CCU60_MCMOUTS = g_vector_table_r_l[ 1 + cSCCB0.Motor_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++;                                                                    
                CCU60_MCMOUTS = g_vector_table_r_l[ 2 + cSCCB0.Motor_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(cSCCB0.Motor_Direction==0)								// direction selected is 'clockwise' 
					CCU60_MCMOUTS = 0x29| 0x0080;							// then energize appropriate coil by sending out the corresponding modulation pattern.
                else														// otherwise if direction selected is 'counter-clockwise'....
                  	CCU60_MCMOUTS = 0x26| 0x0080;						   	// then energize appropriate coil by sending out the corresponding modulation pattern.
                     	
                cSCCB0.Duty_Cyc   = BEMF_CONST_2 - cSCCB0.Start_Duty_Cyc;				// 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.....
				cSCCB0.Duty_Cyc   = PULSE_PERIOD - cSCCB0.Start_Duty_Cyc;				// 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.
                CCU60_CC62SR  = 0xFFFF;										// Load maximum value into CCU6 channel2 register. i.e let the time-out period be maximum to begin with.                            
                CCU60_TCTR4  = 0x0040;										// 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(cSCCB0.Duty_Cyc < DUTY_CYCLE_MIN)
				cSCCB0.Duty_Cyc = DUTY_CYCLE_MIN;
			else if(cSCCB0.Duty_Cyc > DUTY_CYCLE_MAX)
				cSCCB0.Duty_Cyc = DUTY_CYCLE_MAX;
											// switch to page 0
			CCU60_CC63SR = cSCCB0.Duty_Cyc;										// ....load it into the PWM duty cycle reg.
			CCU60_TCTR4 = 0x4000;	
				
            #else // ENABLE_POSITIONING == 1
			cSCCB0.Duty_Cyc  = PULSE_PERIOD - cSCCB0.Start_Duty_Cyc;			// 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.         
			CCU60_CC62SR 	= 0xFFFF;									   	// Load maximum value into CCU6 channel2 register. i.e let the time-out period be maximum to begin with.                                                        
            CCU60_TCTR4  	= 0x0040;										// Run timer T12
			#endif //End of Prepositioning
			break;
        }
        // FREQUENCY RAMP  ***************************************
        // Back-emf checking  
        case 1: 
        {   
			Ramp();       												  
            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 > cSCCB0.Bemf_Check_Freq)						   	// BEMF check freq still not reached?         
			{                                  
            	g_s_counter2++; 
				g_adc_mem			= (ADC0_RESR3 >> 2)&0x003FF;
				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:
        {   
		   	Ramp();
			if(g_s_counter2 > DELAY_TIME_OUT)								// Time out duration elapsed?    
           	{
           		g_state = 4;												// then go to state4 and stop motor.
          	} 
 			g_s_counter2++;
			g_adc_mem			= (ADC0_RESR3 >> 2)&0x003FF;
			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.
						g_time_measure 	= CCU60_T12;						// Save the captured time between two BEMF zero crossings. 
			 			CCU60_TCTR4  	= 0x0006;							// T12 Reset and re-start.
                        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)									// 4 consecutive valid BEMF samples detected? 
                    {
                    	g_slope 		= 0;								// then make slope = '0', so that next we look for rising edge.
						g_time_measure 	= CCU60_T12;						// Save the captured time between two BEMF zero crossings. 
			 			CCU60_TCTR4  	= 0x0006;							// T12 Reset and re-start.                        
                  		g_s_counter1	= 0;	  
               		} 
             	}
            }                                               
          	if(g_time_measure > 0)											// sufficient motor speed achieved ? 
            {	
                CCU60_CC61SR 	= (g_time_measure >> 1) - (DELTA + DELAY);	// Initialise CCU6 channel1 with present motor speed.
                CCU60_CC62SR 	= CCU60_CC61SR + (CCU60_CC61SR >> 2);		// Initialise CCU6 channel2 with with sufficiently higher value to implement time out.
                CCU60_TCTR4 	= 0x0045;									// T12 Reset and Stop (updated CC61R).
				CCU60_TCTR4 	= 0x0002;									// T12 Run.
				CCU60_MCMOUTS 	= g_vector_table_r_l[g_vector + cSCCB0.Motor_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.                          
                CCU60_TCTR4 = 0x4000;
                g_state 	= 3;  
				gb_Closeloop= 1;   
          	}  
           	break;
        }
       	// COMMUTATION WITH BACK-EMF MEASUREMENT ***************************************
        // Continuous operation
        case 3:																   	// Enter state 3 ---- steady state operation.
        {
 			g_adc_mem			= (ADC0_RESR3 >> 2)&0x003FF;	
			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 	= 0;									// reset sample counter.
                        g_slope 		= 3;											// make slope = 3, so that next we start looking for falling edge.
						g_time_measure 	= CCU60_T12;							// save the captured time between two zero crossings.
					    CCU60_CC61SR 	= (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.
                        CCU60_CC62SR 	= CCU60_CC61SR +(CCU60_CC61SR >> 2);						// Initialize CCU6 channel 2 register with sufficiently higher value for time out.
					  	CCU60_TCTR4 	= 0x0045;								// T12 Reset and Stop (updated CC61R).
					    CCU60_TCTR4 	= 0x0002;
						CCU60_MCMOUTS 	= g_vector_table_r_l[g_vector + cSCCB0.Motor_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'.
                        }   
                  	} 
              	}
         	}                                                                   
            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 	= 0;									// reset sample counter.
                        g_slope 		= 2;									// make slope = 3, so that next we start looking for falling edge.
					    g_time_measure 	= CCU60_T12;							// save the captured time between two zero crossings.
						CCU60_CC61SR 	= (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.
                        CCU60_CC62SR  	= CCU60_CC61SR +(CCU60_CC61SR >> 2);
                       	CCU60_TCTR4  	= 0x0045;								// Timer T12 reset and stop.
					    CCU60_TCTR4 	= 0x0002;								// T12 re-start.                                
						CCU60_MCMOUTS 	= g_vector_table_r_l[g_vector + cSCCB0.Motor_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.
            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 PIInitVar(void)
{
 	cSCCB0.Speed.Kp		= DEFAULT_SPEED_KP;
	cSCCB0.Speed.Ki		= DEFAULT_SPEED_KI;
	cSCCB0.Speed.Ymin	= PIC_SPEED_YMIN;
	cSCCB0.Speed.Ymax	= PIC_SPEED_YMAX;

	cSCCB0.Current.Kp	= DEFAULT_CURRENT_KP;
	cSCCB0.Current.Ki	= DEFAULT_CURRENT_KI;
	cSCCB0.Current.Ymin	= PIC_CURRENT_YMIN;
	cSCCB0.Current.Ymax	= PIC_CURRENT_YMAX;
}
#if DAVECG_ControlPanelKBS.POT_ENABLE
void Read_Speed(void)
{
	unsigned int POT_Value,POT_Speed;

	if(ADC0_VFR&0x0002)
	{
		POT_Value = (ADC0_RESR1)& 0x0FFF;

		POT_Speed  =MUL_MAC(POT_Value,SPEED_POT_SCALE);

		if(POT_Speed> SPEED_POT_SCALE)
   			POT_Speed= SPEED_POT_SCALE;

		cSCCB0.Speed_End_Ref=POT_Speed;
	}
}
#endif



