//////////////////////////////////////////////////////////////////////
//********************************************************************
//******************	BC VCH Functions		**********************
//********************************************************************
//////////////////////////////////////////////////////////////////////


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


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

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

#if DAVECG_ControlAlgoKBS.KEIL
//****************************************************************************
// @Imported Global Variables
//****************************************************************************
  extern data 	unsigned int	g_nv_start_ref;	
  extern idata 	unsigned int 	g_nv_end_ref; 		

#if DAVECG_ControlAlgoKBS.CP_ENABLE
 extern xdata 	unsigned char 	CANTrxBuf0[8];
 extern xdata 	unsigned char  	CANTrxBuf1[8];
 extern 		bit 			bitNewCMD0;
 extern data  	unsigned char 	ucNewCMD0;
 #endif

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

  extern 		bit 			bitTimeout;
  extern data 	unsigned char 	Status_word; 

  extern idata	int   		    Rampup_Counter;
  extern const 	unsigned char  	open_loop[];
  extern const 	unsigned char  	closed_loop[];
  extern const 	unsigned char  	exp_hall_patt[];
  extern 		unsigned char 	exp_hp,curr_hp;
  extern data 	unsigned int 	time_measurement;

  extern data  	unsigned int 	g_direction;	
  extern idata 	unsigned int  	g_speed_CC60;
  extern data  	int 			g_current;
  extern xdata 	int 			task_counter;
//****************************************************************************
// @Global Variables
//****************************************************************************
  idata	unsigned int 	g_nv_ref;
  
  //speed measurement
  xdata unsigned int 	g_speed_buffer[6*PP];
  xdata unsigned long 	g_speed_acumm;
  xdata unsigned char 	g_circ_index;
  xdata unsigned char 	g_hall_counter;	

  data  int  			g_duty_cyc;
  data  unsigned char  	ucT2state;
  xdata int	 			g_i_counter;
  unsigned char			exp_hp,curr_hp;	
  xdata 	int 		Ramp_Scheduler;
//****************************************************************************
// @External Prototypes
//****************************************************************************
#if DAVECG_ControlAlgoKBS.CP_ENABLE
#if DAVECG_ControlPanelKBS.EnGraphDisplay 
 extern void CAN_Transmit_MO3();
#endif
 extern void CAN_Transmit_MO1();
 #endif
//****************************************************************************
// @Prototypes Of Local Functions
//****************************************************************************
  
  void MotorControl_vInit( void );
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  void CANInitVar(void);
  #endif
  void CPInitVar(void);
  void MotorStart(void);
  void ControlInit(void);
  void CommInit(void);
  void MotorStop(void);
  #if DAVECG_ControlAlgoKBS.SPEED_CALCU
  int  SpeedCalculation();
  #endif
  #if DAVECG_ControlAlgoKBS.CURRENT_SENSE
  void OverCurrentCheck(void);
  void Current_Measurement(void);
  #endif
  void Rampup();
//****************************************************************************

void MotorControl_vInit( void )
{
	#if DAVECG_DriveKBS.ENABLE_INVERTER
		DAVECG_DriveKBS.PortPinOFF@;
	#endif
  ucT2state = STATEIDLE;
  CPInitVar();
  
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  CANInitVar();
  #else	
  MotorStart();
  #endif
} // End of function MotorControl_vInit();
#if DAVECG_ControlAlgoKBS.CP_ENABLE
void CANInitVar(void)
{
  // slow CAN transfer (every CANTrxBuf0Rate T2 tick)
  // sent at CAN-ID 7
  CANTrxBuf0[0]  = (unsigned char) &Status_word;					
  CANTrxBuf0[1]  = (unsigned char) &Status_word;					
  CANTrxBuf0[2]  = (unsigned char) &g_current;					
  CANTrxBuf0[3]  = (unsigned char) &g_current+1;
  CANTrxBuf0[4]  = (unsigned char) &g_speed_CC60;
  CANTrxBuf0[5]  = (unsigned char) &g_speed_CC60+1;
  CANTrxBuf0[6]  = (unsigned char) &g_current;					
  CANTrxBuf0[7]  = (unsigned char) &g_current+1;

  // fast CAN transfer (every T2 tick)
  // sent at CAN-ID 77
  CANTrxBuf1[0]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar0@;					
  CANTrxBuf1[1]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar1@;					
  CANTrxBuf1[2]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar2@;					
  CANTrxBuf1[3]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar3@;
  CANTrxBuf1[4]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar4@;
  CANTrxBuf1[5]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar5@;
  CANTrxBuf1[6]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar6@;					
  CANTrxBuf1[7]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar7@;

  ucNewCMD0  = 0;
  bitNewCMD0 = 0;

}
#endif

void CPInitVar(void)
{		
	g_nv_end_ref	=	MOTOR_END_REF;					   
	g_nv_start_ref	=	MOTOR_START_REF;				  
	g_direction		=	MOTOR_DIRECTION * DIRECTION_SCALE;			  
	g_nv_ref   =0;

	Status_word=1;
	g_speed_CC60=0;
	Rampup_Counter =VOLTAGE_RAMPUP_COUNT;
}

void MotorStart(void)
{
    ucT2state = STATERUN; 
	SFR_PAGE(_t2_0, noSST);        // switch to page 0
	T2_T2MOD  	=  0x1C;  									//3.25mS
                           
	if(g_nv_start_ref > g_nv_end_ref)                  
    {
    	g_nv_start_ref = g_nv_end_ref;				   // Ensure that 'start_ref' never exceeds 'end_ref'.
    }        
    g_nv_ref        = g_nv_start_ref;
	
	ControlInit();
	CommInit();
	Status_word=0;										//Reset Ctrap, Timeout, overcurrent, wronghall
 	gb_On   = 	1; 
	#if DAVECG_DriveKBS.ENABLE_INVERTER
		DAVECG_DriveKBS.PortPinON@;
	#endif
	bitTimeout=0;
	Ramp_Scheduler=1;
}

 void ControlInit(void) 
{
    int counter = 0;

    for(counter = 0;counter < (PP_FACTOR);counter++)
    {
        g_speed_buffer[counter] = 0;
    }

    g_speed_acumm    = 0x00000008;						   
														   
    g_circ_index     = 0x0000;                   
    g_speed_CC60     = 0x0000;
    g_hall_counter   = 0x0000;

	g_duty_cyc	     = PULSE_PERIOD;                      
    
   	g_i_counter=0;
    task_counter=0;
	g_circ_index=0;
	g_speed_acumm=0;
} 

void CommInit(void)
{
//****************************************************************************
	SFR_PAGE(_cc2, noSST);         							// switch to page 0
    CCU6_MCMCTR = 0x00;               						// CCU6 multi channel mode control
                                        					// enable direct Shadow Tranfers by SW     
	SFR_PAGE(_cc0, noSST);         		  					// switch to page 0
	CCU6_CC61SRLH  =  10;
	CCU6_CC62SRLH  =  CCU6_CC61SRLH + T13_TIME;

	SFR_PAGE(_cc3, noSST);         							// switch to page 0
     CCU6_T12LH     = T13_TIME + 15;						// larger value so that it doesn't generate any
	
	g_duty_cyc = PULSE_PERIOD - g_nv_ref;			

	if (g_duty_cyc < DUTY_CYCLE_MIN) 			 
		g_duty_cyc	= DUTY_CYCLE_MIN;				

	else if(g_duty_cyc > DUTY_CYCLE_MAX)
		g_duty_cyc	= DUTY_CYCLE_MAX;		
													  
                      
	SFR_PAGE(_cc0, noSST);         						  
	CCU6_CC63SRLH = g_duty_cyc;
	
    CCU6_TCTR4L   = 0x40;								   
    CCU6_TCTR4H   = 0x40;
	   
	SFR_PAGE(_pp0, noSST); 
	curr_hp	=	((P1_DATA >> 5) & 0x07);				   // read Hall Pins on startup.
	exp_hp	=	exp_hall_patt[curr_hp + g_direction];
	                               
 	SFR_PAGE(_cc0, noSST);         						   // switch to page 0
	CCU6_MCMOUTSL	=	open_loop[curr_hp + g_direction] | 0x80;
	CCU6_MCMOUTSH	=	(((curr_hp << 3) & 0x38) | exp_hp) | 0x80;
	//-------------------------------------------------------------
	//-------------------------------------------------------------                   
	CCU6_MCMOUTSL	=	closed_loop[curr_hp + g_direction];
	curr_hp	=	exp_hp;
	exp_hp	=	exp_hall_patt[curr_hp + g_direction];
	CCU6_MCMOUTSH	=	(((curr_hp << 3) & 0x38) | exp_hp);	
			
	SFR_PAGE(_cc0, noSST);         							// switch to page 0
    CCU6_TCTR4H   = 0x06;									// T13 Reset/Run --> Start PWM 
	CCU6_TCTR4L	  = 0x00;                                                      

	SFR_PAGE(_cc2, noSST);         							// switch to page 0
    CCU6_MCMCTR  = 0x14;									// Trigger Shadow Tranfers at correct hall
															// event, synchronized to T13 Zero-Match
	CCU6_TRPCTRH	|=	0x80;

	SFR_PAGE(_cc0, noSST);         						   // switch to page 0
    CCU6_TCTR4L   = 0x02;								   // T12 Run
	CCU6_TCTR4H	  = 0x00;
//------------------------------------------------------------------------------------
}

void MotorStop(void)
{
	#if DAVECG_DriveKBS.ENABLE_INVERTER
		DAVECG_DriveKBS.PortPinOFF@;
	#endif
	bitTimeout=0;
	SFR_PAGE(_t2_0, noSST);        // switch to page 0
	T2_T2MOD  	=  0x14;  									//200uS
	ucT2state = STATEIDLE;
	SFR_PAGE(_cc2, noSST);         						   // switch to page 0
    CCU6_MCMCTR = 0x0000;                                  // CCU6 multi channel mode control        
                                                           // Enable Shadow Tranfers direct mode
    
 	SFR_PAGE(_cc0, noSST);         						   // switch to page 0
    CCU6_MCMOUTSL = 0x80;                                  // All Transistors OFF
	CCU6_MCMOUTSH = 0x80;

	CCU6_TCTR4L = 0x05;                                    // CCU6 timer control register 4
    CCU6_TCTR4H	= 0x05;                                    // T13/T12 Reset, T13/T12 Stop -->  No PWM active 
	
	CCU6_CC63SRLH =	PULSE_PERIOD;												   // command is issued.														
														   // command is issued.														
                                    
    CCU6_TCTR4L = 0x00;									   // CCU6 timer control register 4 
    CCU6_TCTR4H = 0x40;                                    // Shadow Tranfers by T13 Zero-Match    
        
     
 	gb_Off	=	1;
 	gb_On   = 	0; 

	g_current=0;
	g_speed_CC60=0;
	g_hall_counter=0;	
	g_nv_ref   =0;
 }
#if DAVECG_ControlAlgoKBS.SPEED_CALCU
int SpeedCalculation()   
{
    unsigned int  l_time = 0;
    long_int_char  l_speed_cal;

    g_speed_acumm  += time_measurement;					   // 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_measurement;       // Preserve the latest sample so that it can be subtracted
														   // out when required.
    if(g_hall_counter < PP_FACTOR)						   // motor still in ramp up stage?
    {
        g_hall_counter = g_hall_counter + 1;			   // then Moving Average Accumulator still hasn't sufficient samples.
        l_time = time_measurement;						   // Hence use the present sample directly, instead of moving average filter. 
        l_speed_cal.U_long = 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.U_long = 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.U_long = SPEED_CONSTANT_AV_FACTOR;        // Load the division factor to calculate motor speed.  
		}
    }
		//using MDU  computation of l_speed_cal / l_time
	//-------------------------------
		SYSCON0	|= 0x01;
		MDU_MD0 = l_speed_cal.st.pr0;
		MDU_MD1 = l_speed_cal.st.pr1;
		MDU_MD2 = l_speed_cal.st.pr2;
		MDU_MD3 = l_speed_cal.st.pr3;
		
		MDU_MD4_MD5 = l_time;
		while(MDU_BSY==1);
							
		MDU_MDUSTAT &= 0x04;
		MDU_MDUCON   = 0x12;
	    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'.
    	}
		
			
		while((MDU_MDUSTAT & 0x01) == 0);
		
		l_time= MDU_MR0_MR1;
		SYSCON0 &= 0xfe; 
	//-------------------------------
	
    return (l_time);                         // finally compute motor speed.
	
}
#endif
#if DAVECG_ControlAlgoKBS.CURRENT_SENSE
void OverCurrentCheck(void)
{
    if (g_current >= CURRENT_MAX)						   // motor instantaneous current higher than
    {													   // specified limit ?
        g_i_counter++;									   // if yes, increment s/w counter.
        if (g_i_counter == TIME_CURRENT_MAX)			   // s/w counter reached the specified limit ?
        {
			 gb_overcurrent = 1;						   
		     MotorStop();								   
        }
    }
    else												   // if motor 'current' sample is not higher
    {													   // than the specified limit....
        if (g_i_counter > 0)							   // then.....
        {
            g_i_counter--;								   // ....decrement the s/w counter.
        }
    }
}
void Current_Measurement(void)
{
		 	SFR_PAGE(_ad2, noSST);
	 		g_current = (((((uword)ADC_RESR0H << 2)|(ADC_RESR0L>>6))<<3) & 0x7fff); // Read ADC Result.
	 
	 		SFR_PAGE(_ad6, noSST);
	 		ADC_CRCR1 = 0x10;
	 		
			OverCurrentCheck(); 
				
}
#endif
void Rampup()
{

	if(Ramp_Scheduler>=Rampup_Counter)	 
	{
		if(g_nv_end_ref > g_nv_ref)						// End ref not reached?
		{                                                      
			g_nv_ref += 1;								// then increment.                     
		}                                                                                 
		if(g_nv_end_ref < g_nv_ref)						// actual ref greater than end ref?
		{                                                                         
			g_nv_ref -= 1;								// then decrement.  
		}                 
		g_duty_cyc = PULSE_PERIOD - g_nv_ref;			// Convert actual voltage ref to duty cycle.
	
 		Ramp_Scheduler=1;
	}
	else
		Ramp_Scheduler++;


  }
#endif
#if DAVECG_ControlAlgoKBS.SDCC

//****************************************************************************
// @Imported Global Variables
//****************************************************************************
  extern data at 0x0028		unsigned int 	g_nv_start_ref;	
  extern idata 	at 0x008C	unsigned int 	g_nv_end_ref; 		
  extern data 	at 0x0020	unsigned char 	Status_word; 
  extern idata 	at 0x8E		int   		    Rampup_Counter;
  extern data 	at 0x2E 	unsigned int 	g_direction;							   // Index-offset for reading the switching pattern, as per specified motor direction.
  extern idata 	at 0x90 	unsigned int  	g_speed_CC60;
  extern data 	at 0x2C 	int 			g_current;

#if DAVECG_ControlAlgoKBS.CP_ENABLE
  extern xdata 	unsigned char 	CANTrxBuf0[8];
  extern xdata 	unsigned char  	CANTrxBuf1[8];
  extern 		bit 			bitNewCMD0;
  extern data  	unsigned char 	ucNewCMD0;
#endif
  //control Parameter

  extern 			bit 			gb_hs_error;
  extern 			bit 			gb_ctrap;
  extern 			bit	 			gb_time_out;
  extern 			bit 			gb_On;
  extern 			bit 			gb_Off;
  extern 			bit				gb_overcurrent;

  extern 			bit 			bitTimeout;

  extern const 	unsigned char  	open_loop[];
  extern const 	unsigned char  	closed_loop[];
  extern const 	unsigned char  	exp_hall_patt[];
  extern data 	unsigned int 	time_measurement;
  extern xdata 	int 			task_counter;
//****************************************************************************
// @Global Variables
//****************************************************************************
  data	unsigned int 	g_nv_ref;
  
  //speed measurement
  xdata unsigned int	g_speed_buffer[6*PP];
  xdata unsigned long	g_speed_acumm;
  xdata unsigned char	g_circ_index;
  xdata unsigned char	g_hall_counter;	

  data  int  			g_duty_cyc;
  data unsigned char	ucT2state;
  xdata int				g_i_counter;	
  unsigned char			exp_hp,curr_hp;	
  xdata 	int 		Ramp_Scheduler;
//****************************************************************************
// @External Prototypes
//****************************************************************************
#if DAVECG_ControlAlgoKBS.CP_ENABLE
#if DAVECG_ControlPanelKBS.EnGraphDisplay 
 extern void CAN_Transmit_MO3();
#endif
 extern void CAN_Transmit_MO1();
 #endif
//****************************************************************************
// @Prototypes Of Local Functions
//****************************************************************************
  
  void MotorControl_vInit( void );
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  void CANInitVar(void);
  #endif

  void  CPInitVar(void);
  void  MotorStart(void);
  void  ControlInit(void);
  void  CommInit(void);
  void  MotorStop(void);
  #if DAVECG_ControlAlgoKBS.SPEED_CALCU
  int   SpeedCalculation();
  #endif
  #if DAVECG_ControlAlgoKBS.CURRENT_SENSE
  void  OverCurrentCheck(void);
  void Current_Measurement(void);
  #endif
  void Rampup();
//****************************************************************************

void MotorControl_vInit( void )
{
	#if DAVECG_DriveKBS.ENABLE_INVERTER
		DAVECG_DriveKBS.PortPinOFF@;
	#endif
  ucT2state = STATEIDLE;
  CPInitVar();
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  CANInitVar();
  #else	
  MotorStart();
  #endif

} // End of function MotorControl_vInit();
#if DAVECG_ControlAlgoKBS.CP_ENABLE
void CANInitVar(void)
{
  // slow CAN transfer (every CANTrxBuf0Rate T2 tick)
  // sent at CAN-ID 7
  CANTrxBuf0[0]  = (unsigned char) &Status_word;					
  CANTrxBuf0[1]  = (unsigned char) &Status_word;					
  CANTrxBuf0[2]  = (unsigned char) &g_current+1;					
  CANTrxBuf0[3]  = (unsigned char) &g_current;
  CANTrxBuf0[4]  = (unsigned char) &g_speed_CC60+1;
  CANTrxBuf0[5]  = (unsigned char) &g_speed_CC60;
  CANTrxBuf0[6]  = (unsigned char) &g_speed_CC60+1;					
  CANTrxBuf0[7]  = (unsigned char) &g_speed_CC60;

  // fast CAN transfer (every T2 tick)
  // sent at CAN-ID 77
  CANTrxBuf1[0]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar0@;					
  CANTrxBuf1[1]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar1@;					
  CANTrxBuf1[2]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar2@;					
  CANTrxBuf1[3]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar3@;
  CANTrxBuf1[4]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar4@;
  CANTrxBuf1[5]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar5@;
  CANTrxBuf1[6]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar6@;					
  CANTrxBuf1[7]  = (unsigned char) &DAVECG_ControlAlgoKBS.CANMsgVar7@;

  ucNewCMD0  = 0;
  bitNewCMD0 = 0;
}
#endif
void CPInitVar(void)
{		
	g_nv_end_ref	=	MOTOR_END_REF;					   
	g_nv_start_ref	=	MOTOR_START_REF;				  
	g_direction		=	MOTOR_DIRECTION * DIRECTION_SCALE;			  
	Status_word=0;
	gb_time_out		=	0;
  	gb_On			=	0;
  	gb_Off			=	1;
	gb_ctrap 		=	0;
	gb_hs_error		=	0;
    gb_overcurrent	=	0;

	g_speed_CC60=0;
	Rampup_Counter =VOLTAGE_RAMPUP_COUNT;
}

void MotorStart(void)
{
    ucT2state = STATERUN; 
	SFR_PAGE(_t2_0, noSST);        // switch to page 0
	T2_T2MOD  	=  0x1C;  									//3.25mS
	if(g_nv_start_ref > g_nv_end_ref)                  
    {
    	g_nv_start_ref = g_nv_end_ref;				   // Ensure that 'start_ref' never exceeds 'end_ref'.
    }        
    g_nv_ref        = g_nv_start_ref;
	ControlInit();
	CommInit();
 	gb_Off	=	0;
 	gb_On   = 	1; 
	gb_time_out		=	0;
  	gb_ctrap 		=	0;
	gb_hs_error		=	0;
    gb_overcurrent	=	0;
	                           
	#if DAVECG_DriveKBS.ENABLE_INVERTER
		DAVECG_DriveKBS.PortPinON@;
	#endif
	bitTimeout=0;
	Ramp_Scheduler=1;
}

 void ControlInit(void) 
{
    int counter = 0;

    for(counter = 0;counter < (PP_FACTOR);counter++)
    {
        g_speed_buffer[counter] = 0;
    }

    g_speed_acumm    = 0x00000008;						   
														   
    g_circ_index     = 0x0000;                   
    g_speed_CC60     = 0x0000;
    g_hall_counter   = 0x0000;

	g_duty_cyc	     = PULSE_PERIOD;                      
    
 
 	g_i_counter=0;
    task_counter=0;
	g_circ_index=0;
	g_speed_acumm=0;
} 

void CommInit(void)
{
//****************************************************************************
	SFR_PAGE(_cc2, noSST);         							// switch to page 0
    CCU6_MCMCTR = 0x00;               						// CCU6 multi channel mode control
                                        					// enable direct Shadow Tranfers by SW     
	SFR_PAGE(_cc0, noSST);         		  					// switch to page 0
	
	CCU6_CC61SRLH =10;

	
	CCU6_CC62SRLH  =  CCU6_CC61SRLH + T13_TIME;				// 32 = T13_TIME;
	

	SFR_PAGE(_cc3, noSST);         							// switch to page 0
     CCU6_T12LH     = T13_TIME + 15;						// larger value so that it doesn't generate any
	
															// larger value so that it doesn't generate any
	g_duty_cyc = PULSE_PERIOD - g_nv_ref;			
	if (g_duty_cyc < DUTY_CYCLE_MIN) 			 
		g_duty_cyc	= DUTY_CYCLE_MIN;				

	else if(g_duty_cyc > DUTY_CYCLE_MAX)
		g_duty_cyc	= DUTY_CYCLE_MAX;		
														   // interrupt immediately.
                        
	SFR_PAGE(_cc0, noSST);         						  
	CCU6_CC63SRLH =	g_duty_cyc;								// to zero % duty cycle.

    CCU6_TCTR4L   = 0x40;								   // select the events to trigger shadow transfers of T12 & T13.
    CCU6_TCTR4H   = 0x40;
	   
	SFR_PAGE(_pp0, noSST); 
	curr_hp	=	((P1_DATA >> 5) & 0x07);				   // read Hall Pins on startup.
	exp_hp	=	exp_hall_patt[curr_hp + g_direction];
	                               
 	SFR_PAGE(_cc0, noSST);         						   // switch to page 0
	CCU6_MCMOUTSL	=	open_loop[curr_hp + g_direction] | 0x80;
	CCU6_MCMOUTSH	=	(((curr_hp << 3) & 0x38) | exp_hp) | 0x80;
	//-------------------------------------------------------------
	//-------------------------------------------------------------                   
	CCU6_MCMOUTSL	=	closed_loop[curr_hp + g_direction];
	curr_hp	=	exp_hp;
	exp_hp	=	exp_hall_patt[curr_hp + g_direction];
	CCU6_MCMOUTSH	=	(((curr_hp << 3) & 0x38) | exp_hp);	
			
	SFR_PAGE(_cc0, noSST);         							// switch to page 0
    CCU6_TCTR4H   = 0x06;									// T13 Reset/Run --> Start PWM 
	CCU6_TCTR4L	  = 0x00;                                                      

	SFR_PAGE(_cc2, noSST);         							// switch to page 0
    CCU6_MCMCTR  = 0x14;									// Trigger Shadow Tranfers at correct hall
															// event, synchronized to T13 Zero-Match
	CCU6_TRPCTRH	|=	0x80;

	SFR_PAGE(_cc0, noSST);         							// switch to page 0
    CCU6_TCTR4L   = 0x02;									// T12 Run
	CCU6_TCTR4H	  = 0x00;
//------------------------------------------------------------------------------------
}

void MotorStop(void)
{
	#if DAVECG_DriveKBS.ENABLE_INVERTER
		DAVECG_DriveKBS.PortPinOFF@;
	#endif
	bitTimeout=0;
	SFR_PAGE(_t2_0, noSST);        // switch to page 0
	T2_T2MOD  	=  0x14;  									//200uS
	ucT2state = STATEIDLE;
	SFR_PAGE(_cc2, noSST);         							// switch to page 0
    CCU6_MCMCTR = 0x0000;									// CCU6 multi channel mode control        
															// Enable Shadow Tranfers direct mode
    
 	SFR_PAGE(_cc0, noSST);         							// switch to page 0
    CCU6_MCMOUTSL = 0x80;									// All Transistors OFF
	CCU6_MCMOUTSH = 0x80;

	CCU6_TCTR4L = 0x05;										// CCU6 timer control register 4
    CCU6_TCTR4H	= 0x05;										// T13/T12 Reset, T13/T12 Stop -->  No PWM active 
	
     CCU6_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    
        
     
 	gb_Off	=	1;
 	gb_On   = 	0; 

	g_current=0;
	g_speed_CC60=0;
	g_hall_counter=0;	
	g_nv_ref   =0;
 }
#if DAVECG_ControlAlgoKBS.SPEED_CALCU
int SpeedCalculation()   
{

    unsigned int  l_time = 0;
    long_int_char  l_speed_cal;

    g_speed_acumm  += time_measurement;					   // 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_measurement;       // Preserve the latest sample so that it can be subtracted
														   // out when required.
    if(g_hall_counter < PP_FACTOR)						   // motor still in ramp up stage?
    {
        g_hall_counter = g_hall_counter + 1;			   // then Moving Average Accumulator still hasn't sufficient samples.
        l_time = time_measurement;						   // Hence use the present sample directly, instead of moving average filter. 
        l_speed_cal.U_long = 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.U_long = 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.U_long = SPEED_CONSTANT_AV_FACTOR;        // Load the division factor to calculate motor speed.  
		}
    }
	
	//using MDU l_speed_cal / l_time
	//-------------------------------
		SYSCON0	|= 0x01;
		MDU_MD0 = l_speed_cal.st.pr3;
		MDU_MD1 = l_speed_cal.st.pr2;
		MDU_MD2 = l_speed_cal.st.pr1;
		MDU_MD3 = l_speed_cal.st.pr0;
		
		MDU_MD4_MD5 = l_time;
		while(MDU_BSY==1);
							
		MDU_MDUSTAT &= 0x04;
		MDU_MDUCON   = 0x12;
	    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'.
    	}
		
			
		while((MDU_MDUSTAT & 0x01) == 0);
		
		l_time= MDU_MR0_MR1;
	  SYSCON0 &= 0xfe; 
	//-------------------------------
	 return (l_time);											// finally compute motor speed.
	
}
#endif
#if DAVECG_ControlAlgoKBS.CURRENT_SENSE
void OverCurrentCheck(void)
{
    if (g_current >= CURRENT_MAX)						   // motor instantaneous current higher than
    {													   // specified limit ?
        g_i_counter++;									   // if yes, increment s/w counter.
        if (g_i_counter == TIME_CURRENT_MAX)			   // s/w counter reached the specified limit ?
        {
			 gb_overcurrent = 1;						   
		     MotorStop();								   
        }
    }
    else												   // if motor 'current' sample is not higher
    {													   // than the specified limit....
        if (g_i_counter > 0)							   // then.....
        {
            g_i_counter--;								   // ....decrement the s/w counter.
        }
    }
}
void Current_Measurement(void)
{
	SFR_PAGE(_ad2, noSST);
	g_current = (((((uword)ADC_RESR0H << 2)|(ADC_RESR0L>>6))<<3) & 0x7fff); // Read ADC Result.
	 
	SFR_PAGE(_ad6, noSST);
	ADC_CRCR1 = 0x10;
	 			
	OverCurrentCheck(); 
}
#endif
void Rampup()
{

	if(Ramp_Scheduler>=Rampup_Counter)	 
	{
	if(g_nv_end_ref > g_nv_ref)						// End ref not reached?
	{                                                      
		g_nv_ref += 1;								// then increment.                     
	}                                                                                 
	if(g_nv_end_ref < g_nv_ref)						// actual ref greater than end ref?
	{                                                                         
		g_nv_ref -= 1;								// then decrement.  
	}                 
	g_duty_cyc = PULSE_PERIOD - g_nv_ref;			// Convert actual voltage ref to duty cycle.

 	Ramp_Scheduler=1;
	}
	else
		Ramp_Scheduler++;


  }

#endif