//*****************************************************************************/
// @Module         Speed Control
// @Filename       SCB_CTRL.C
// @Controller     XC88x Series
//
//
// @Description    This file contains functions for Speed control through 
//                 Block Commutation
//*****************************************************************************/
//****************************************************************************
// @Includes
//****************************************************************************
#include "MAIN.H"
//****************************************************************************/
// @Imported Global Variables
//****************************************************************************/
extern unsigned char const g_vector_table_r_l[];		   // MOSFET switching pattern

#if DAVECG_CONTROL_PANEL_ENABLE
extern bit gb_motor_status;								   // bit variable which reflects/controls motor start/stop status.
extern C_BDATA g_trigger_status;						   // bit variable which triggers sampling/capture of graph variable.
#else
C_UBDATA g_trigger_status;                                 //trigger status word
C_SBIT gb_motor_status		C_ATBIT(g_trigger_status, 5);  //motor status flag
#endif
//****************************************************************************/
// @Local Function Prototypes
//****************************************************************************/
void motor_start(void);
void motor_stop(void);
void comm_init(void);
unsigned int speed_calculation(unsigned int time_measurement, U_CHAR *speed_counter, int limit);
void init_control(void);
void motor_ramp_generation(void);
unsigned int pi_controller_16bit(long *buf_ptr,reference,act);
void start_up(void);
void ramp(void);
void commutation(void);
#if DAVECG_CURRENT_SENSE
void OVER_CURRENT_CHECK(void);
#endif
//****************************************************************************
// @Imported Function Prototypes
//****************************************************************************


//****************************************************************************
// @Global Variables
//****************************************************************************
C_BDATA g_status_word;
unsigned char g_once;
int C_SDATA g_i_counter;								   // s/w counter to specify the time limit for motor 'Over Current'.
unsigned char g_direction;								   // Index-offset for reading the switching pattern, as per specified motor direction.
C_UBDATA  g_direction_user;								   // variable to specify the desired motor direction.
unsigned int idata g_current;
C_UBDATA g_trap_reset;									   // set this variable to '1', to reset the 'Latched CTRAP' condition.
int C_SDATA g_increment_free;
int C_SDATA g_counter0;									   // s/w time base used in motor start-up in BEMF mode.
unsigned int idata g_duty_cyc;
unsigned int idata g_speed_setref;							   // variable which reflects the present 'motor speed'.
unsigned int idata g_nv_end_ref;						   // variable to specify the desired 'motor end speed'.
unsigned int idata g_nv_start_ref0;						   // variable to memorize 'motor end speed'.
unsigned int idata g_nv_start_ref;						   // variable to specify the desired 'motor start speed'.
unsigned char g_circ_index;								   // Index to access the circular buffer used in motor speed computation.
unsigned int g_speed_buffer[6*PP];						   // s/w array(memory) for preserving the previous samples of motor speed.
unsigned long C_SDATA g_time_step;						   // variable to store the result(in counts) of "ramp up time" computation.
unsigned long C_SDATA g_counter1;						   // s/w timer to implement ramp up time.
unsigned long g_speed_acumm;							   // s/w accumulator for averaging of motor speed.
unsigned long idata g_ramp_up_time;						   // variable to specify the desired 'ramp up time'.
// Declaration of bit-variables required to store motor status.
C_SBIT gb_on           C_ATBIT(g_status_word, 8);          // ON                           
C_SBIT gb_off          C_ATBIT(g_status_word, 9);          // OFF                           
C_SBIT gb_idle_state   C_ATBIT(g_status_word, 10);         // Idle_state
C_SBIT gb_hs_error     C_ATBIT(g_status_word, 11);         // Wrong hall event          
C_SBIT gb_time_out     C_ATBIT(g_status_word, 12);         // Time_out detection
C_SBIT gb_ctrap        C_ATBIT(g_status_word, 13);         // Ctrap detection
C_SBIT gb_overcurrent  C_ATBIT(g_status_word, 14);         // Overcurrent detection
 
unsigned int idata g_pi_controller_out;

int idata g_volt_increment;								   // variable to hold BEMF volage increment value.
int idata  g_adc_mem;									   // specifies the next phase/channel in which we need to look for zero crossing.

U_CHAR g_speed_counter;									   // Intermediate variable to determine whether notor speed is 'too less(negligible)' or 'considerable'.
int idata g_freq_increment;								   // variable to hold BEMF frequency increment value.
unsigned int idata  g_slope;							   // specifies whether we should look for 'rising' edge of zero crossing or the 'falling' edge.
unsigned int idata g_state;  
unsigned int idata  g_speed_CC61;						   // variable store the actual motor speed information.
unsigned int idata g_bemf_check_freq;					   // variable to hold BEMF check frequency value.
unsigned int idata g_bemf_end_freq;						   // variable to hold BEMF end frequency value.

unsigned int idata g_start_duty_c;						   // specifies the starting duty cycle for motor startup in BEMF mode.
unsigned int idata g_back_emf_measure;					   // specifies the sampled zero crossing voltage.
unsigned int idata g_bemf_aux;							   // Intermediate variable to determine when it is time to look in next phase for zero crossing signal.
unsigned int idata g_v_counter;							   // s/w time base to increment the 'voltage' in BEMF startup mode.
unsigned int idata g_f_counter;							   // s/w time base to increment the 'frequency' in BEMF startup mode.
unsigned int idata g_adc_ctr_bemf;						   // specifies which ADC channel needs to be sampled next for BEMF signal.
unsigned int idata g_state;								   // specifies the state of the 'commutation' state machine.
unsigned int g_time_measure;							   // Holds the captured 'time between zero crossings'.
unsigned int idata g_vector;							   // Index used to access the switching pattern from the pattern table.
unsigned int idata g_angle_inc;							   // variable to hold BEMF angle increment value.
unsigned int idata g_start_freq;                           // specifies the initial start frequency for motor startup in BEMF mode.
unsigned int idata g_freq_step;							   // Intermediate s/w time base used in 'quadratic ramp' implementation.
unsigned int idata g_s_counter0;						   // s/w time base used in 'pre-positioning' stage of commutation.
unsigned int idata g_s_counter1;						   // s/w time base used in 'pre-positioning' stage of commutation.
unsigned int idata g_s_counter2;						   // s/w time base used in 'pre-positioning' stage of commutation.
long idata g_start_angle;								   // time base(used in ramp function) to specify when to output next modulation pattern.   
unsigned char idata injection_channel_select;
unsigned int idata compare_value;
unsigned int idata high_limit;
unsigned int idata low_limit;
U_CHAR task_counter;

int idata g_test_kp;									   // variable to hold user specified PI proportional Gain.        
int idata g_test_ki;									   // variable to hold user specified PI integral Gain.            
int idata  g_test_ymax;									   // variable to hold user specified PI saturation upper limit.   
int idata  g_test_ymin;									   // variable to hold user specified PI saturation lower limit.   

pi_con idata g_pi_array;
extern int pi_task_counter;

//****************************************************************************

//****************************************************************************
#define CONDITION_OPERATOR <
#define SPEED_CONSTANT_AV_FACTOR	(SPEED_CONSTANT_AV * 8) 
#define INDEX_LIMIT	((6*PP) -1)
//****************************************************************************
// @Function        void motor_start(void)
// Description		This Function executes the functions required for Motor
//					start-up such as initialization of motor related variables,
//					initialization of motor related SFRs etc.
//					It also ensures that 'motor_start_ref' is always lesser
//					than the 'motor_end_ref'.
//----------------------------------------------------------------------------
void motor_start(void)
{
	if (g_once == 0x0)
	{
		g_once = 0x01;
        g_status_word = 0x0001;                            // Set 'gb_on' flag to convey to the user that 'motor_start' command is issued.
        if(g_nv_start_ref > g_nv_end_ref)                  // Start reference limitation
        {
            g_nv_start_ref = g_nv_end_ref;				   // Ensure that 'start_ref' never exceeds 'end_ref'.
        }        
        g_nv_start_ref0 = g_nv_start_ref;                  // make another copy of start voltage reference.
        g_speed_setref =  g_nv_start_ref;  				   // Set start speed reference into actual speed reference.           

        init_control();                                    // initialisation of all the variables required for motor start up.
		comm_init();
		TR2 = 1;										   // start timer T2
		pi_task_counter=2;
		SFR_PAGE(_ad6, noSST); 
	  	ADC_CRMR1   = ADC_CRMR1| 0x05;  
	}
} // motor_start
//****************************************************************************
// @Function        void motor_stop(void)
// Description		This function implements the functions required for motor
//					stop such as switching off the PWM, all MOSFETs, stopping
//					all timers etc.
//----------------------------------------------------------------------------
void motor_stop(void)
{
	SFR_PAGE(_cc2, noSST);         						   // switch to page 2
    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_CC63SRLH = 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.														
    CCU6_TCTR4L = 0x00;                                    // CCU6 timer control register 4 
    CCU6_TCTR4H = 0x40;                                    // Shadow Tranfers by T13 Zero-Match    

	TR2 = 0;										       //   stop timer T2

    	
    if(gb_motor_status == 1)							   // if motor stop command detected, clear g_once so that it executes                                      
    {                                                      // motor start function when user issues start command.
        g_once = 0x00;                                     
    }
	
	gb_off	= 1;                                           // Status update
    gb_on	= 0;                                           // Status update
	
 } // motor_stop
//****************************************************************************
// @Function        void commutation_init(void)
// Description		This function initialises the SFRs required for motor start-up
//					such as loading of the Modulation register, enabling of the Timers,
//					enabling of the Interrupts etc.
//----------------------------------------------------------------------------
void comm_init(void)
{
//----------------------------------------------------------------------------
	SFR_PAGE(_cc2, noSST);         						   // switch to page 2
    CCU6_MCMCTR  = 0x0014;								   // Trigger Shadow Tranfers at correct hall
	#if DAVECG_ENABLE_TRAP
	CCU6_TRPCTRH	|=	0x80;
	#endif	//TRAP
	SFR_PAGE(_cc0, noSST);         						   // switch to page 0
	CCU6_MCMOUTSL	=	0x002C | 0x80;
    CCU6_TCTR4H   = 0x06;								   // T13 Reset/Run --> Start PWM 
	CCU6_TCTR4L	  = 0x00;                                                      

}
//****************************************************************************
// @Function        void init_control(void)
// Description		This function initialises the various variables required 
//					for motor start up.
//----------------------------------------------------------------------------
void init_control(void) 
{
    
    int l_i = 0;

    for(l_i = 0;l_i < (6 * PP);l_i++)
    {
        g_speed_buffer[l_i] = 0;
    }
    g_speed_acumm    = 0x00000008;						   // initialise speed accumulator with
    g_speed_counter  = 0x0000;
    g_speed_CC61     = 0x0000;							   // Reset the variable which holds 'Speed' to zero.
    g_counter1       = 0x00000000;
														   // 8 so that division by 8 won't result in zero.
    g_circ_index     = 0x0000;                   
    g_speed_CC61     = 0x0000;							   // Reset the variable which holds 'Speed' to zero.
    g_time_step      = 0x00000000;
    
    g_duty_cyc		 =  BEMF_CONST_1 - g_start_duty_c;                   

    g_back_emf_measure = 0x0000;						   // Reset the variable which holds the measured 'BEMF voltage' to zero.
    g_bemf_aux       = 0x0000;						       // Reset the variable which holds the previous commutation pattern to zero.		
    g_v_counter      = 0x0000;							   // Reset the voltage ramp counter to zero.                                                                                                                 
    g_f_counter      = 0x0000;							   // Reset the frequency ramp counter to zero.                                                                                                                 
    g_state          = 0x0000;							   // Reset the commutation state holder to zero.
    g_slope          = 0x0000;							   // Reset the commutation slope holder to zero.
    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;
    g_i_counter     = 0x0000;							   // s/w time base for over-current is cleared to '0'.    
   	if(g_direction_user > 1)
    {
        g_direction_user = 1;							   // Ensure that g_direction_user never takes an invalid value.
    }     
	g_direction		=	g_direction_user * 8;
	g_pi_array.intg_buffer.S_long = 0;
	task_counter 	= 0;
    
}                                                          // End of function init_control
//****************************************************************************
// @Function        void motor_ramp_generation(void)
// Description		This function verifies whether the user has entered a new 
//					'end reference' and accordingly ramps up the duty cycle,
//					to reach the new 'end reference'
//----------------------------------------------------------------------------
void motor_ramp_generation(void)
{

    int l_ref_difference = 0;
    unsigned long l_co_instructions = 0;
    if(g_speed_counter >= (18*PP))								//if the motor initial startup is successful.       
    {
        if(g_increment_free == 1)								//if the hardware timer interrupt has occured.
        {
          g_increment_free = 0;
          g_counter1 += 64;
        }

        if(g_counter1 >= g_time_step)							//if the 'timestep'(Delta) for ramping has elapsed.
        {
          //-------speed_ref_ramp----------						//then inc/dec the reference speed by one count.
		    if(g_nv_end_ref > g_speed_setref)					// End ref not reached?
		    {                                                                         
		    g_speed_setref += 1;								// then increment.  
		    }                                                                                 
		    if(g_nv_end_ref < g_speed_setref)					// actual ref greater than end ref?
		    {                                                                         
		    g_speed_setref -= 1;								// then decrement.  
		    }                                                                                 
          g_counter1 = 0;										//and reset the 'timestep' s/w counter.
        }

		if(g_nv_start_ref0 != g_nv_end_ref)						//if the end reference i.e motor end speed has been
        {														//changed by the user.

		  l_ref_difference	= g_nv_end_ref - g_nv_start_ref0;
		  if(l_ref_difference < 0)
			{
			  l_ref_difference = -l_ref_difference;
			}

          g_time_step = g_ramp_up_time  / l_ref_difference;		//then calculate the 'time step' as per the new 
          g_nv_start_ref0 = g_nv_end_ref;						//'difference in speed'
		  														// here MDU should be used for division.....
        } 
		


    }
}//  End of function motor_ramp_generation
//****************************************************************************
// @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_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.
            }
        }
    }
    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'.
		    }
		//----------------------------------    
	} 
}//  End of function ramp.
//****************************************************************************
// @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_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 = 0x003E | 0x0080;                           // then energize appropriate coil by sending out the corresponding modulation pattern.                                  
                     }
                     else													   // otherwise if direction selected is 'counter-clockwise'....
                     {
                    CCU6_MCMOUTSL = 0x003B | 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++;

            #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 3
                             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)								   // 4 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 ? 
            {																   // then let us make arrangements to enter into state 3.             
			     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.                          
                 g_state = 3;                                                  // finally make state = 3.

			}  
            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);						   // then read the BEMF signal.
			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.
								SFR_PAGE(_cc3, noSST);         		  		   // switch to page 3
                                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 + (CCU6_CC61SRLH >> 2);	// Initialize CCU6 channel 2 register with sufficiently higher value for time out.
                                CCU6_TCTR4L  = 0x45;                          // T12 Reset and Stop (updated CC61R).
								CCU6_TCTR4L  = 0x02;                          // T12 re-start.                                
                                
								CCU6_MCMOUTSL = g_vector_table_r_l[g_vector + g_direction];  
																			   // Update MCMOUTS register.
                                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 rising edge detection.
                                 g_s_counter1 = 0;                             // reset sample counter.
                                 g_slope = 2;                                  // make slope = 2, so that next we start looking for rising edge.                 
								 SFR_PAGE(_cc3, noSST);         		  	   // switch to page 3.
                                 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;	// Initialise the CCU6 channel1 register with the present motor speed value.
                                 CCU6_CC62SRLH  = CCU6_CC61SRLH + (CCU6_CC61SRLH >> 2);
																			   // Initialise the CCU6 channel2 register with sufficiently higher value for time out.
                                 CCU6_TCTR4L   = 0x45;						   // Timer T12 reset and stop.
								 CCU6_TCTR4L   = 0x02;						   // T12 restart (from the updated value).
								 CCU6_MCMOUTSL = g_vector_table_r_l[g_vector + g_direction]; 
                                 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.
            {
                motor_stop();												   // execute motor stop function.
                gb_motor_status = 1;										   // 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 STATE ( SWITCH-OFF) ***************************************
            default:
            {
                motor_stop();    
                gb_motor_status = 1;										   // Invalid State....Hence Stop Motor.
                gb_time_out = 1;            
                break;
            }
        }
} //  End of Commutation.
//****************************************************************************

//****************************************************************************
// @Function        void speed_calculation(void)
// Description		This function computes the actual motor speed from the
//					measured 'time between two Hall events'. It also implements
//					a moving average filter to suppress any invalid spikes from 
//					the Hall sensor.	
//----------------------------------------------------------------------------
unsigned int speed_calculation(unsigned int time_measurament, U_CHAR *speed_counter, int limit)   
{
	#if DAVECG_SPEED_CALCU
    unsigned int  l_time = 0;
    unsigned long l_speed_cal = 0;

    g_speed_acumm  += time_measurament;					   // 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] = time_measurament;       // Preserve the latest sample so that it can be subtracted
														   // out when required.
    if(*speed_counter < limit)							   // motor still in ramp up stage?
    {
        *speed_counter = *speed_counter + 1;			   // then Moving Average Accumulator still hasn't sufficient samples.
        l_time = time_measurament;						   // 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 = 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.  
		}
    }
    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.
	#else
	return(0);											   // Speed Calculation feature has been disabled.
	#endif	//SPEED_CALCU

}                                                          // End of function speed_calculation 

//---------INLINE FUNCTIONS of CTRL.H begin--------------------------------------------------
//*************************************************************************************************
void CONTROL_PANEL_PARAMS(void);
void INIT_CTRL_VAR(void);
void motor_ramp_generation(void);
void MCU_INIT(void);
void CCU6_CTRL_REG(void);
#if DAVECG_CONTROL_PANEL_ENABLE
extern void trace(void);								   
#endif
//*************************************************************************************************

//*************************************************************************************************
#define		REQUESTED				1
#define		RESET					0
#define		MOTOR_READY_TO_START	0
#define		MOTOR_STOPPED			1
//*************************************************************************************************
//*************************************************************************************************

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

//*************************************************************************************************
// @Function        void INIT_PI_VAR(void)     
// Description		This function initialises the PI gain & Limit variables with the corresponding 
//					user entered values from the Run time control panel dialog of DID.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void INIT_PI_VAR(void) 
{
    g_pi_array.ymax  = PIC_YMAX;						   // Initialise the PI upper limit variable. 
    g_pi_array.ymin  = PIC_YMIN;						   // Initialise the PI lower limit variable. 
    g_pi_array.kp    = INIT_SPEED_KP;					   // Initialise the PI proportional gain variable. 
    g_pi_array.ki    = INIT_SPEED_KI;					   // Initialise the PI integral gain variable. 
}
//*************************************************************************************************
// @Function        void INIT_CTRL_VAR(void)     
// Description		This function initialises the various intermediate variables that are required to 
//					be set to pre-defined default values before any motor related operation.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
void INIT_CTRL_VAR(void)
{
	INIT_PI_VAR();										   // execute PI initialisation routine.
    g_start_duty_c	= 0x0;								   // Initialize BEMF start_duty_cycle to '0'.             
    g_direction		= 0x0;								   // Initialise default motor direction to 'clockwise'.   
    g_once			= 0x0;								   // Clear the variable 'once' so that by default         
						  								   // motor stop is assumed.                              
    g_status_word	= 0x0002;							   // Initialise status flags to reflect motor stopped condition.
	CONTROL_PANEL_PARAMS();								   // execute control panel dependent variable initialisation routine.
	BEMF_PARAM_INIT();									   // execute Back EMF related variable initialisation routine.
}
//*************************************************************************************************       
//*************************************************************************************************
//*************************************************************************************************
// @Function        void CCU6_CTRL_REG(void)     
// Description		This function initialises the various SFRs of CC6 peripheral that are required 
//					to be set to pre-defined default values before any motor related operation.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
void CCU6_CTRL_REG(void)
{
/*  CCU6_T12DTC  =  CCU6_T12DTC_VAL; 
  CCU6_T13PR   =  PULSE_PERIOD; 
  CCU6_TCTR0   =  T12_CLOCK; 
  CCU6_T12PR   =  TIM_OUT; 
  CCU6_PSLR    =  PASSIVE_STATE; 
  CCU6_MODCTR  =  MOD_CONTROL; 
  CCU6_TRPCTR  =  0x3F07; 
  CCU6_TCTR2   =  0x0000;*/
}
//*************************************************************************************************
// @Function        void MCU_INIT(void)     
// Description		This function initialises UART for desired BAUD RATE.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
void MCU_INIT(void)
{
	#if DAVECG_CONTROL_PANEL_ENABLE
	sio_init();											   // Initialize the UART module.
	#endif
}
//*************************************************************************************************
#if DAVECG_CURRENT_SENSE
//*************************************************************************************************
//*************************************************************************************************
// @Function        void OVER_CURRENT_CHECK(void)     
// Description		This Function implements the logic required for 'over current' detection.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
void OVER_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 ?
        {
			gb_overcurrent = 1;							   // Set the 'overcurrent' flag to convey 
														   // the same to the control panel
            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.
            
        }
    }
    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.
        }
    }
}
#endif