//*****************************************************************************/
// @Module         Speed Current Control
// @Filename       SCCB_CTRL.C
// @Controller     XC16x Series
//
//
// @Description    This file contains functions for SpeedCurrent control through 
//                 Block Commutation
//*****************************************************************************/
//****************************************************************************
// @Includes
//****************************************************************************
#include "MAIN.H"

//****************************************************************************/
// @Imported Global Variables
//****************************************************************************/

#if DAVECG_TLE
extern int C_SDATA g_alt_sel0_P1L;
extern int C_SDATA g_alt_sel0_P1L_del;
#endif // TLE == 1

extern int 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;								   // bit variable which triggers sampling/capture of graph variable. 
C_SBIT gb_motor_status C_ATBIT(g_trigger_status, 5);  	   // bit variable which reflects/controls motor start/stop status.
#endif

//****************************************************************************/
// @Local Function Prototypes
//****************************************************************************/

void motor_start(void);
void motor_stop(void);

void commutation_init(void);
int speed_calculation(unsigned int time_measurement, int *speed_counter, int limit);
void init_control(void);
void motor_ramp_generation(void);

#if DAVECG_CURRENT_SENSE
void adc_offset(void);
#endif // CURRENT_SENSE == 1


void start_up(void);
void ramp(void);
void commutation(void);

void speed_ref_ramp(void);
void blink_led(void);

//****************************************************************************
// @Imported Function Prototypes

#if DAVECG_TLE
extern void driver_enable(void);
#endif // TLE == 1

#if DAVECG_CONTROL_PANEL_ENABLE
extern void iiup(void);
#endif


//****************************************************************************
// @Global Variables
//****************************************************************************

C_BDATA g_status_word;
int C_SDATA g_current_max;
int C_SDATA g_once;										   // bit word containing all motor status bits.
int C_SDATA g_i_counter;								   // s/w counter to specify the time limit for motor 'Over Current'.
int C_SDATA g_direction;								   // Index-offset for reading the switching pattern, as per specified motor direction.
int C_SDATA g_direction_user;							   // variable to specify the desired motor direction.
int C_SDATA g_pic_speed_out;
int C_SDATA g_current;									   // variable which stores the 'motor current' information.
int C_SDATA g_trap_reset;								   // set this variable to '1', to reset the 'Latched CTRAP' condition.
int C_SDATA g_increment_free;							   // s/w flag to specify that T13 interrupt has occured.

int C_SDATA g_counter0;									   // s/w time base used in motor start-up in BEMF mode.
int C_SDATA g_pic_current_out;

unsigned int C_SDATA g_duty_cycle;						   // The desired PWM Duty Cycle is reflected in this variable.
unsigned int C_SDATA g_nv_end_ref;
unsigned int C_SDATA g_nv_start_ref;
unsigned int C_SDATA g_nv_start_ref0;
unsigned int C_SDATA g_circ_index;						   // Index to access the circular buffer used in motor speed computation.
unsigned int C_SDATA g_speed_buffer[6*PP];				   // s/w array(memory) for preserving the previous samples of motor speed.
unsigned int C_SDATA g_speed_ref;						   // variable to specify the desired 'motor speed'.

long C_SDATA g_adc_offset_res;							   // Computed ADC offset is stored in this variable.
long C_SDATA g_adc_offset_acumm;						   // s/w accumulator for averaging of ADC offset.

unsigned long C_SDATA g_time_step;
unsigned long C_SDATA g_counter1;
unsigned long C_SDATA g_speed_acumm;					   // s/w accumulator for averaging of motor speed.

unsigned long C_SDATA g_ramp_up_time;

// Declaration of bit-variables required to store motor status.
C_SBIT gb_on           C_ATBIT(g_status_word, 0);          // ON                           
C_SBIT gb_off          C_ATBIT(g_status_word, 1);          // OFF                           
C_SBIT gb_idle_state   C_ATBIT(g_status_word, 2);          // Idle_state
C_SBIT gb_hs_error     C_ATBIT(g_status_word, 3);          // Wrong hall event          
C_SBIT gb_time_out     C_ATBIT(g_status_word, 4);          // Time_out detection
C_SBIT gb_ctrap        C_ATBIT(g_status_word, 5);          // Ctrap detection
C_SBIT gb_overcurrent  C_ATBIT(g_status_word, 6);          // Overcurrent detection 


#if DAVECG_TLE
int C_SDATA g_i_mpattern;
#endif

int C_SDATA g_speed_counter;
int C_SDATA g_adc_mem;									   // specifies the next phase/channel in which we need to look for zero crossing.
int C_SDATA g_volt_increment;							   // variable to hold BEMF volage increment value.
int C_SDATA g_freq_increment;							   // variable to hold BEMF frequency increment value.
unsigned int C_SDATA g_speed_CC61;						   // variable to store the actual motor speed information.
unsigned int C_SDATA g_bemf_check_freq;					   // variable to hold BEMF check frequency value.
unsigned int C_SDATA g_bemf_end_freq;					   // variable to hold BEMF end frequency value.
unsigned int C_SDATA g_start_duty_c;					   // specifies the starting duty cycle for motor startup in BEMF mode.
unsigned int C_SDATA g_back_emf_measure;				   // specifies the sampled zero crossing voltage.
unsigned int C_SDATA g_bemf_aux;						   // Intermediate variable to determine when it is time to look in next phase for zero crossing signal.
unsigned int C_SDATA g_v_counter;						   // s/w time base to increment the 'voltage' in BEMF startup mode.
unsigned int C_SDATA g_f_counter;						   // s/w time base to increment the 'frequency' in BEMF startup mode.
unsigned int C_SDATA g_adc_ctr_bemf;					   // specifies which ADC channel needs to be sampled next for BEMF signal.
unsigned int C_SDATA g_state;							   // specifies the state of the 'commutation' state machine.
unsigned int C_SDATA g_slope;							   // specifies whether we should look for 'rising' edge of zero crossing or the 'falling' edge.
unsigned int C_SDATA g_time_measure;					   // Holds the captured 'time between zero crossings'.
unsigned int C_SDATA g_vector;							   // Index used to access the switching pattern from the pattern table.
unsigned int C_SDATA g_angle_inc;						   // variable to hold BEMF angle increment value.
unsigned int C_SDATA g_start_freq;                         // specifies the initial start frequency for motor startup in BEMF mode.
unsigned int C_SDATA g_freq_step;						   // Intermediate s/w time base used in 'quadratic ramp' implementation.
unsigned int C_SDATA g_s_counter0;						   // s/w time base used in 'pre-positioning' stage of commutation.
unsigned int C_SDATA g_s_counter1;						   // s/w time base used in 'pre-positioning' stage of commutation.
unsigned int C_SDATA g_s_counter2;						   // s/w time base used in 'pre-positioning' stage of commutation.
long C_SDATA g_start_angle;								   // time base(used in ramp function) to specify when to output next modulation pattern.   

unsigned char C_SDATA injection_channel_select;
unsigned int C_SDATA COMPARE_VALUE;
unsigned int C_SDATA HIGH_LIMIT;
unsigned int C_SDATA LOW_LIMIT;



int C_SDATA g_test_speed_kp;							   // variable to hold user specified PI proportional Gain.
int C_SDATA g_test_speed_ki;							   // variable to hold user specified PI integral Gain.
int C_SDATA g_test_speed_ymax;							   // variable to hold user specified PI saturation upper limit.
int C_SDATA g_test_speed_ymin;							   // variable to hold user specified PI saturation lower limit.

int C_SDATA g_test_current_kp;							   // variable to hold user specified PI proportional Gain.
int C_SDATA g_test_current_ki;							   // variable to hold user specified PI integral Gain.
int C_SDATA g_test_current_ymax;						   // variable to hold user specified PI saturation upper limit.
int C_SDATA g_test_current_ymin;						   // variable to hold user specified PI saturation lower limit.
extern struct pi_controller                                // PI-controller parameter            
{                                                                                
    long yn;											   // PI integral buffer.  
    int  kp;                                               // Proportional Gain          
    int  ki;											   // Integral Gain          
    int  ymax;                                             // Maximal ouput limit    
    int  ymin;                                             // Minimal ouput limit    
};
struct pi_controller C_SDATA g_pi_speed_array;
struct pi_controller C_SDATA g_pi_current_array;

//****************************************************************************
//****************************************************************************
// @Function        void TRAP_CTRL_REG_SETUP(void)     
// Description		This Function enables the TRAP feature of CCU6 module.
//----------------------------------------------------------------------------
INLINE void TRAP_CTRL_REG_SETUP(void)
{
#if DAVECG_ENABLE_TRAP
	CCU6_TRPCTR |= 0x8000;								   // Enable CTRAP.
#endif // ENABLE_TRAP == 1
}
//****************************************************************************
//****************************************************************************
// @Function        void ADC_DATA(void)     
// Description		This Function specifies the ADC channel to be configured
//					in injection mode.
//----------------------------------------------------------------------------
INLINE void ADC_DATA(int x)
{
#if DAVECG_CURRENT_SENSE
		ADC_DAT2 = (x);									   // Specify the ADC channel to be 'Injected'.
#endif // CURRENT_SENSE ==1
}
//****************************************************************************
//****************************************************************************
// @Function        void CCU6_CC6SR_LOAD_VALUE(void)     
// Description		This Function initialises the CCU6 - shadow registers 
//					with appropraite count values.
//----------------------------------------------------------------------------
INLINE void CCU6_CC6SR_LOAD_VALUE(void)
{
}
//****************************************************************************
//****************************************************************************
// @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 == 0)										   //execute only once when 'motor_start' command is issued.                                                                 
    {    
        
        g_once = 0x0001;                                   // Set the flag so that this code never executes until next 'motor_start' command.
        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_ref =  g_nv_start_ref;  				   // Set start speed reference into actual speed reference.           
        
        DRIVER_ENABLE();								   // Enable the driver IC if required.
        init_control();                                    // initialisation of all the variables required for motor start up.
        commutation_init();								   // initialisation of all SFRs required for motor start up.
        
    }
        
} // 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)
{

#if DAVECG_TLE
#if DAVECG_ENABLE_REFRESH_PULSE
	    PORT_ALT_SELECT();								   // Configure the port pins required for Drive refresh as output pins.
        DRIVE_REFRESH_SETUP();							   // Execute the refresh sequence for the Driver IC.
#endif // DAVECG_ENABLE_REFRESH_PULSE
#endif // DAVECG_TLE

    CCU6_MCMCTR = 0x0000;                                  // CCU6 multi channel mode control        
                                                           // Enable Shadow Tranfers direct mode
    
    CCU6_MCMOUTS = 0x8080;                                 // All Transistors OFF
  
    CCU6_TRPCTR &= 0x7FFF;                                 // Trap disable                                                                               
    
	CCU6_TCTR4 = 0x0505;                                   // CCU6 timer control register 4
                                                           // T13/T12 Reset, T13/T12 Stop -->  No PWM active 

    CC2_T78CON = 0x0000;                                   // load CAPCOM2 timer 7 and timer 8 control 
                                                           // register  -  T7 stop
    
    CC2_T7 = T7_PERIOD;                                    // load CAPCOM2 timer 7 register  50 us

    CCU6_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.														
                                    
    CCU6_TCTR4 = 0x4000;                                   // CCU6 timer control register 4 
                                                           // Shadow Tranfers by T13 Zero-Match    
        
    
    gb_off	= 1;                                           // Status update
    gb_on	= 0;                                           // Status update

    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 = 0x0000;                                     
    }                                                                    

    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;					   // Initialise g_direction as per the motor-direction set by user.  

} // 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 commutation_init(void)
{

#if DAVECG_ENABLE_TRAP
    TRAP_CTRL_REG_SETUP();                                  // Enable CCU6 trap
#endif
  CCU6_MCMCTR  = 0x0014;
#if DAVECG_TLE
  CCU6_MCMOUTS = 0x0024 | 0x0080;                          // Load start modulation pattern 
#elif DAVECG_BTS
  CCU6_MCMOUTS = 0x002C | 0x0080;                          // Load start modulation pattern 
#endif // if TLE / elif BTS
 
  CCU6_TCTR4   = 0x0600;                                   // load CCU6 timer control register 4 T13 Reset, T13 Run --> Start PWM   
  CC2_T78CON   = 0x0040;                                   // load CAPCOM2 timer 7 and timer 8 control 
                                                           // register T7 Run
#if DAVECG_CURRENT_SENSE
#if DAVECG_BTS
  ADC_DATA(0x3000);                                         // load ADC control register 2
#elif DAVECG_TLE
 ADC_DATA(0x4000);
#endif                                                     // if BTS / elif TLE
#endif                                                     // CURRENT_SENSE == 1
 
}                                                          //  End of function Commutation_init

//****************************************************************************
// @Function        void init_control(void)
// Description		This function initialises the various variables required 
//					for motor start up.
//----------------------------------------------------------------------------
void init_control(void) 
{

    
#if DAVECG_SPEED_CALCU
    int l_i = 0;
    for(l_i = 0;l_i < (6 * PP);l_i++)
    {
        g_speed_buffer[l_i] = 0;						   // clear the array(buffer) used to implement averaging of 'speed' samples.
    }
    g_speed_acumm    = 0x00000008;						   // initialise speed accumulator with
														   // 8 so that division by 8 won't result in zero.
    g_circ_index     = 0x0000;							   // let the circular index (array pointer) be reset to zero.                   


#endif //SPEED_CALCU == 1 
    g_counter1       = 0x00000000;
    g_time_step      = 0x00000000;
    
#if DAVECG_SPEED_CALCU
    g_speed_counter  = 0x0000;
    g_speed_CC61     = 0x0000;
#endif
    g_duty_cycle     =  BEMF_CONST_1 - g_start_duty_c;	   // Calculate the Initial duty cycle.                  

    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_adc_ctr_bemf   = 0x9691;							   // Let the BEMF channel pointer be initialized to channel 1.
    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;


#if DAVECG_BTS
    
    g_adc_ctr_bemf   = 0x9691;  
  g_pic_speed_out       = 0x00000000;                                      
    g_pi_speed_array.yn   = 0x00000000;					   // clear the PI integral buffer
    g_pi_current_array.yn = (g_start_duty_c * 49152);
    
#endif // BTS == 1

//*****************************************************
    
#if DAVECG_TLE
    g_adc_ctr_bemf   = 0x9691;
    
  g_pic_speed_out       = 0x00000000;                                      
    g_pi_speed_array.yn   = 0x00000000;					   // clear the PI integral buffer
    g_pi_current_array.yn = (g_start_duty_c * 49152);  
 #if DAVECG_CURRENT_SENSE
    g_i_mpattern    = 0x0000;
#endif //  CURRENT_SENSE == 1
   
#endif // TLE == 1

    


#if DAVECG_CURRENT_SENSE
    g_i_counter     = 0x0000;							   // s/w time base for over-current is cleared to '0'.    
#endif //  CURRENT_SENSE == 1
     
    
} // End of function init_control


//****************************************************************************
// @Function        void speed_ref_ramp(void)
// Description		This function increments/decrements the actual speed
//					reference until it becomes equal to the speed end ref.
//----------------------------------------------------------------------------
void speed_ref_ramp(void)
{
    if(g_nv_end_ref > g_speed_ref)                         // End ref not reached?
    {                                                                         
    g_speed_ref += 1;                                      // then increment.  
    }                                                                                 
    if(g_nv_end_ref < g_speed_ref)                         // actual ref greater than end ref?
    {                                                                         
    g_speed_ref -= 1;                                      // then decrement.  
    }                                                                                 

    
} //  End of function Speed_ref_ramp
//****************************************************************************
// @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;
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 increment the reference speed by one count
          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.
#if DAVECG_KEIL
          C_CoLOAD_0_1(0, C_LSHIFT(g_nv_end_ref, 16));	   //then calculate the new 'difference in speed' the 
          C_CoSUB_0_1(0, C_LSHIFT(g_nv_start_ref0, 16));   //motor has to achieve.
          C_CoABS(); 
#endif
#if DAVECG_TASKING
          l_co_instructions = (unsigned int)g_nv_end_ref;  //then calculate the new 'difference in speed' the 
          _CoLOAD(l_co_instructions << 16);				   //motor has to achieve.
          l_co_instructions = (unsigned int)g_nv_start_ref0; 
          _CoSUB(l_co_instructions << 16);
          _CoABS();
#endif
          l_ref_difference = C_CoSTOREMAS();
          if(l_ref_difference > 1)
          { 
            l_ref_difference -= 1;       
          }
          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'
        }
    }

}//  End of function motor_ramp_generation

//****************************************************************************
// @Function        void blink_led(void)
// Description		This function complements the LED port pin after the set
//					time has elapsed.
//----------------------------------------------------------------------------
void blink_led(void)
{
// LED Blink
    if(g_counter0 > 32000)								   // set time elapsed?
    {              
#if DAVECG_XC164CS
    P1L     ^= 0x0040;									   // then complement LED pin.
#endif
#if DAVECG_XC164CM
    P1L     ^= 0x0040;									   // then complement LED pin.
#endif
#if DAVECG_XC167CI
    P9      ^= 0x0010;									   // then complement LED pin.
#endif
    g_counter0 = 0x0000;								   // and reset the s/w time base.
    }
    g_counter0++;										   // increment s/w time base.
}

//****************************************************************************
// @Function        void start_up(void)   
// Description		This function reads the next Modulation Pattern from the 
//					vector table and loads it into the MCMOUT shadow register.
//					It then increments the index for the vector table.
//----------------------------------------------------------------------------
void start_up(void)  
{
    CCU6_MCMOUTS = g_vector_table_r_l[g_vector + g_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 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 Exp ramp).
#else
                     g_freq_step++;                        
                     g_angle_inc  += g_freq_step >> 4;     // then increment angle.( for Linear ramp).
#endif 
                 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_cycle--;                           // 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
        start_up();                                        // and output the next modulation pattern.
    } 
}

//****************************************************************************
// @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;
                }
                                  
                if(g_s_counter1 == 1)										   // time to output the next modulation pattern.
                {               
                     g_s_counter1++;        
                     CCU6_MCMOUTS = 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_MCMOUTS = 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' ?
                     {

#if DAVECG_BTS
                    CCU6_MCMOUTS = 0x003E | 0x0080;                            // then energize appropriate coil by sending out the corresponding modulation pattern.                                  
#endif // DAVECG_BTS


#if DAVECG_TLE
                    CCU6_MCMOUTS = 0x0016 | 0x0080;							   // then energize appropriate coil by sending out the corresponding modulation pattern.                                  
#endif // DAVECG_TLE
                     }
                     else													   // otherwise if direction selected is 'counter-clockwise'....
                     {
#if DAVECG_BTS
                    CCU6_MCMOUTS = 0x003B | 0x0080;							   // then energize appropriate coil by sending out the corresponding modulation pattern.                                                                                               
#endif // DAVECG_BTS
#if DAVECG_TLE
                    CCU6_MCMOUTS = 0x0029 | 0x0080;                            // then energize appropriate coil by sending out the corresponding modulation pattern.                                                                    
#endif // DAVECG_TLE
                     }
                     g_duty_cycle = 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_cycle = 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_CC62SR = 0xFFFF;									   // Load maximum value into CCU6 channel2 register. i.e let the time-out period be maximum to begin with.                            
                     CCU6_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++;

            #else // ENABLE_POSITIONING == 1
                 g_duty_cycle = 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.         
                 CCU6_CC62SR = 0xFFFF;									       // Load maximum value into CCU6 channel2 register. i.e let the time-out period be maximum to begin with.                                                        
                 CCU6_TCTR4  = 0x0040;										   // Run timer T12
            #endif // ENABLE_POSITIONING == 1
            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.
            }      

            ramp();															   // otherwise ramp up the motor duty cycle & frequency.

            if(g_angle_inc > g_bemf_check_freq)								   // BEMF check freq still not reached?         
            {                                  
                g_s_counter2++;                                                                      
                g_back_emf_measure  = (g_adc_mem & 0x0FFC);					   // 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_back_emf_measure = (g_adc_mem & 0x0FFC);						   // 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 == 10)								   // 10 consecutive valid BEMF samples detected? 
                       {
                             g_slope = 1;									   // then make slope = '1', so that next we look for falling edge.                             
                             g_time_measure = CCU6_T12;						   // Save the captured time between two BEMF zero crossings. 
                             CCU6_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 == 10)								   // 10 consecutive valid BEMF samples detected? 
                       {
                             g_slope = 0;                                      // then make slope = '0', so that next we look for rising edge.
                             g_time_measure = CCU6_T12;						   // Save the captured time between two BEMF zero crossings. 
                             CCU6_TCTR4  = 0x0006;							   // T12 Reset and re-start.                        
                             g_s_counter1 = 0;
                       } 
                 }
            }                                               
            if(g_time_measure > 0)											   // sufficient motor speed achieved ? 
            {																   // then let us make arrangements to enter into state 3.             
                 CCU6_CC61SR = (g_time_measure >> 1) - (DELTA + DELAY);        // Initialise CCU6 channel1 with present motor speed.
                 CCU6_CC62SR = CCU6_CC61SR + (CCU6_CC61SR >> 2);               // Initialise CCU6 channel2 with with sufficiently higher value to implement time out.
                 CCU6_TCTR4  = 0x0045;                                         // T12 Reset and Stop (updated CC61R).
                 CCU6_TCTR4  = 0x0002;                                         // T12 Run.
                 CCU6_MCMOUTS = 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.
        {
            if(g_slope == 0)												   // Are we looking for rising edge ?
            {                                                                                                 
                 g_back_emf_measure  = (g_adc_mem & 0x0FFC);				   // then read the BEMF signal.
                 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 = CCU6_T12;					   // save the captured time between two zero crossings.
                                CCU6_CC61SR = (CCU6_T12 >> 1) - DELAY;         // Initialize the CCU6 channel 1 register with the present motor speed value,
																			   // so that it generates interrupt for every zero crossing.
                                CCU6_CC62SR = CCU6_CC61SR + (CCU6_CC61SR >> 2);// Initialize CCU6 channel 2 register with sufficiently higher value for time out.
                                CCU6_TCTR4  = 0x0045;                          // T12 Reset and Stop (updated CC61R).
                                CCU6_TCTR4  = 0x0002;                          // T12 re-start.                                
                                CCU6_MCMOUTS = 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'.
                                }                                     
                          } 
                     }
                }                                                                   
                if(g_slope == 1)											   // Are we looking for falling edge ?
                {                                                                                 
                     g_back_emf_measure  = (g_adc_mem & 0x0FFC);			   // then read the BEMF signal.
                     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.                 
                                 g_time_measure = CCU6_T12;                    // save the captured time between two zero crossings.          
                                 CCU6_CC61SR  = (CCU6_T12 >> 1) - DELAY;	   // Initialise the CCU6 channel1 register with the present motor speed value.
                                 CCU6_CC62SR  = CCU6_CC61SR + (CCU6_CC61SR >> 2);
																			   // Initialise the CCU6 channel2 register with sufficiently higher value for time out.
                                 CCU6_TCTR4   = 0x0045;						   // Timer T12 reset and stop.
                                 CCU6_TCTR4   = 0x0002;						   // T12 restart (from the updated value).
                                 CCU6_MCMOUTS = 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:
            {
            }
        }

    } 
//****************************************************************************
// @Function        void duty_cycle_update(void)
//
//----------------------------------------------------------------------------
void duty_cycle_update(void)
{
// Duty cycle update 

#if DAVECG_KEIL
    C_CoLOAD_1_0(g_duty_cycle, 0);
    C_CoMIN_1_0(DUTY_CYCLE_MAX, 0);
    C_CoMAX_1_0(DUTY_CYCLE_MIN, 0);
    CCU6_CC63SR  = _lmac_();
    CCU6_TCTR4  = 0x4000;                                 // CCU6 timer control register 4
                                                          // Shadow Tranfers T13 enable    
#endif //KEIL == 1
#if DAVECG_TASKING
    Int_CoLimit(0,g_duty_cycle,DUTY_CYCLE_MIN,DUTY_CYCLE_MAX);
    CCU6_CC63SR = _CoSTOREMAS();
    CCU6_TCTR4  = 0x4000;                                 // CCU6 timer control register 4
                                                          // Shadow Tranfers T13 enable    
#endif //TASKING == 1

}//  End of function duty_cycle_update

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

    g_speed_acumm  += time_measurament;					   // Accumulate the new sample i.e measured time b/w two zero crossings.
														   // 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 * 8;           // Load the division factor to calculate motor speed.  
		}
    }
    g_circ_index++;                                        // Increment index for circular buffer
    if(g_circ_index > ((6 * PP) - 1))					   // 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.

}                                                          // End of function speed_calculation 
#endif
//****************************************************************************
// @Function        void adc_offset(void)
// Description		This function computes the ADC offset value, by taking 
//					65,535 samples of the ADC measured data. This computed
//					offset value is preserved in the variable g_adc_offset_res.
//----------------------------------------------------------------------------
#if DAVECG_CURRENT_SENSE
void adc_offset(void)
{
    unsigned int l_i = 0;
    unsigned int l_j = 0;
    g_adc_offset_acumm = 0;								   // clear s/w accumulator.
    for(l_i = 0; l_i < 65534; l_i++)					   // until all samples not accumulated, be in the loop.
    {
        ADC_CTR0_ADST = 1;								   // Issue 'start sampling' command to ADC.
        for(l_j = 0; l_j < 80; l_j++)					   // give some time for ADC to complete conversion.
        {
            NOP();
        }
        g_adc_offset_acumm += ((ADC_DAT & 0x0FFC) << 3);   // accumulate(integrate) the next sample.
    }
    g_adc_offset_res = g_adc_offset_acumm >> 16;		   // compute the average of all the samples.
}
#endif //(CURRENT_SENSE == 1)
//****************************************************************************


