//////////////////////////////////////////////////////////////////////
//************************************************************************
//*******************		BC SCH Functions		**********************
//************************************************************************
//////////////////////////////////////////////////////////////////////


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


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

#if DAVECG_ControlAlgoKBS.KEIL
//****************************************************************************
// @Imported Global Variables
//****************************************************************************
  extern data 	unsigned int	g_speed_start_ref;	
  extern idata 	unsigned int 	g_speed_end_ref; 		
 
  extern idata  unsigned int 	speed_kp;
  extern idata  unsigned int 	speed_ki;

#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

  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_pi_controller_out;

  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_speed_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;
  xdata pi_con 			g_pi_array;	
  data 	unsigned char 	exp_hp,curr_hp;
  xdata int 			Ramp_Scheduler;
#if DAVECG_ControlPanelKBS.POT_ENABLE
 data unsigned char		speed_adc_H,speed_adc_L;
 data unsigned char		speed_adc_buf_H,speed_adc_buf_L;
 data unsigned int		Speed_Ref_POT;
#endif
//****************************************************************************
// @External Prototypes
//****************************************************************************
#if DAVECG_ControlAlgoKBS.CP_ENABLE
 #if DAVECG_ControlPanelKBS.EnGraphDisplay 
 extern void CAN_Transmit_MO3();
#endif
 extern void CAN_Transmit_MO1();
 #endif
 extern unsigned int PIControllerSpeed(long *buf_ptr,unsigned int reference,unsigned int act);

//****************************************************************************
// @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);
  int SpeedCalculation();

  void INIT_PI_VAR(void);
  	#if DAVECG_ControlAlgoKBS.CURRENT_SENSE
  void Current_Measurement(void);
  void OverCurrentCheck(void);
#endif
  void Rampup();
#if DAVECG_ControlPanelKBS.POT_ENABLE
  void Read_Speed(void);
#endif
//****************************************************************************

void MotorControl_vInit( void )
{
  #if DAVECG_DriveKBS.InvActiveLow
  DAVECG_DriveKBS.PortPinON@;
  #endif
  #if DAVECG_DriveKBS.InvActiveHigh
  DAVECG_DriveKBS.PortPinOFF@;
  #endif 
  ucT2state = STATEIDLE;
  CPInitVar();
  INIT_PI_VAR();
  #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)
{		
	#if DAVECG_ControlPanelKBS.POT_ENABLE
	Read_Speed();
	#else
	g_speed_end_ref	=	MOTOR_END_REF;					   
	#endif				   
	g_speed_start_ref	=	MOTOR_START_REF;				  
	g_direction		=	MOTOR_DIRECTION * DIRECTION_SCALE;			  
	g_speed_ref   =0;

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

void MotorStart(void)
{
    ucT2state = STATERUN; 
	SFR_PAGE(_t2_0, noSST);        // switch to page 0
	T2_T2MOD  	=  0x1C;  									//3.25mS
	                    
	if(g_speed_start_ref > g_speed_end_ref)                  
    {
    	g_speed_start_ref = g_speed_end_ref;				   // Ensure that 'start_ref' never exceeds 'end_ref'.
    }        
    g_speed_ref        = g_speed_start_ref;
	
	ControlInit();
	CommInit();

	Status_word=0;												//Reset Ctrap, Timeout, overcurrent, wronghall
 	gb_On   = 	1; 
    #if DAVECG_ControlPanelKBS.POT_ENABLE
	TR2=0;
	#endif
// enable inverter
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.PortPinOFF@;
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.PortPinON@;
	#endif
	bitTimeout=0;
	Ramp_Scheduler=1;

}

 void ControlInit(void) 
{
    int counter = 0;

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

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

	g_duty_cyc	     = PULSE_PERIOD;                      
    
	g_pi_array.intg_buffer.S_long = 0;
 	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 3
     CCU6_T12LH     = T13_TIME + 15;													   // larger value so that it doesn't generate any
													  
                        
	SFR_PAGE(_cc0, noSST);         						  
    CCU6_CC63SRLH  = PULSE_PERIOD;					 
														  

    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)
{
// Disable inverter
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.PortPinON@;
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.PortPinOFF@;
	#endif
	bitTimeout=0;
	ucT2state = STATEIDLE;
	SFR_PAGE(_t2_0, noSST);        // switch to page 0
	T2_T2MOD  	=  0x14;  									//200uS
	
	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; 
    #if DAVECG_ControlPanelKBS.POT_ENABLE
	TR2=1;
	#endif

   
	g_current=0;
	g_speed_CC60=0;
	g_hall_counter=0;	
	g_speed_ref   =0;
 }

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.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; 
	//-------------------------------
	//l_time=	l_speed_cal / l_time;
	 
   return (l_time);                         // finally compute motor speed.
  
}
#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 INIT_PI_VAR(void) 
{
    g_pi_array.ymax  = PIC_SPEED_YMAX;							// Initialise the PI upper limit variable. 
    g_pi_array.ymin  = PIC_SPEED_YMIN;							// Initialise the PI lower limit variable. 
    speed_kp    = INIT_SPEED_KP;								// Initialise the PI proportional gain variable. 
    speed_ki    = INIT_SPEED_KI;								// Initialise the PI integral gain variable. 
}
void Rampup()
{
	if(Ramp_Scheduler>=Rampup_Counter)	 
	{
	if(g_speed_end_ref > g_speed_ref)							// End ref not reached?
	{                                                      
		g_speed_ref += 1;										// then increment.                     
	}                                                                                 
	if(g_speed_end_ref < g_speed_ref)							// actual ref greater than end ref?
	{                                                                         
		g_speed_ref -= 1;										// then decrement.  
	}
 	Ramp_Scheduler=1;
	}
	else
	Ramp_Scheduler++;
 }	
#if DAVECG_ControlPanelKBS.POT_ENABLE
 void Read_Speed(void)
{
	SFR_PAGE(_ad2, noSST);
	if(ADC_RESR1L & 0x10)
	{	
	   	SFR_PAGE(_ad2, noSST);
	 	speed_adc_H=ADC_RESR1H;
	 	speed_adc_L=ADC_RESR1L&0xC0;
	 	if((speed_adc_buf_L!=speed_adc_L)||(speed_adc_buf_H!=speed_adc_H))
		{
		 	speed_adc_buf_L=speed_adc_L;
	 		speed_adc_buf_H=speed_adc_H;
	 		SYSCON0	|= 0x01;
			//-------------------------------
			MDU_MR0 = speed_adc_L;
			MDU_MR1 = speed_adc_H;

			MDU_MD4 = SPEED_POT_SCALE_L;
			MDU_MD5 = SPEED_POT_SCALE_H;
			while(MDU_BSY==1);
								
			MDU_MDUSTAT &= 0x04;
			MDU_MDUCON   = 0x10;		
			while((MDU_MDUSTAT & 0x01) == 0);
			Speed_Ref_POT =(MDU_MR3<<8)+MDU_MR2;
				
			//-------------------------------
			SYSCON0 &= 0xfe;	
	 	
	 		if(Speed_Ref_POT>SPEED_MAX_TARGET)
		   		Speed_Ref_POT=SPEED_MAX_TARGET;
	
		   	g_speed_end_ref=Speed_Ref_POT;
			
		}
								 
				
	}
}

#endif
#endif 
#if DAVECG_ControlAlgoKBS.SDCC
//****************************************************************************
// @Imported Global Variables
//****************************************************************************
  extern data at 0x0028		unsigned int 	g_speed_start_ref;	
  extern idata at 0x008C 	unsigned int 	g_speed_end_ref; 		
  extern idata at 0x0092	unsigned int 	speed_kp;
  extern idata at 0x0094	unsigned int 	speed_ki;
  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 data  	unsigned char 	ucNewCMD0;
  extern 		bit 			bitNewCMD0;
  #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 data  unsigned int		g_pi_controller_out;
 
  extern xdata 	int 			task_counter;
//****************************************************************************
// @Global Variables
//****************************************************************************
  data	unsigned int 	g_speed_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;	
  xdata pi_con 			g_pi_array;	
  data 	unsigned char 	exp_hp,curr_hp;
  xdata int 			Ramp_Scheduler;
  #if DAVECG_ControlPanelKBS.POT_ENABLE
  data unsigned char	speed_adc_H,speed_adc_L;
  data unsigned char	speed_adc_buf_H,speed_adc_buf_L;

  data unsigned int		Speed_Ref_POT;
  #endif
//****************************************************************************
// @External Prototypes
//****************************************************************************
#if DAVECG_ControlAlgoKBS.CP_ENABLE
 #if DAVECG_ControlPanelKBS.EnGraphDisplay 
 extern void CAN_Transmit_MO3();
#endif
 extern void CAN_Transmit_MO1();
 #endif
 extern  unsigned int PIControllerSpeed(long *buf_ptr,unsigned int reference,unsigned int act);
//****************************************************************************
// @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);
  int   SpeedCalculation();

  void INIT_PI_VAR(void) ;
  #if DAVECG_ControlAlgoKBS.CURRENT_SENSE
  void Current_Measurement(void);
  void  OverCurrentCheck(void);
  #endif

  void Rampup();
#if DAVECG_ControlPanelKBS.POT_ENABLE
  void Read_Speed(void);
#endif
//****************************************************************************

void MotorControl_vInit( void )
{
  // Disable inverter
  #if DAVECG_DriveKBS.InvActiveLow
  DAVECG_DriveKBS.PortPinON@;
  #endif
  #if DAVECG_DriveKBS.InvActiveHigh
  DAVECG_DriveKBS.PortPinOFF@;
  #endif
  ucT2state = STATEIDLE;
  CPInitVar();

  INIT_PI_VAR();
  #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_current+1;					
  CANTrxBuf0[7]  = (unsigned char) &g_current;

  // 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_speed_end_ref	=	MOTOR_END_REF;					   
	g_speed_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_ref   =0;
	g_speed_CC60=0;

	Rampup_Counter =SPEED_RAMPUP_COUNT;

}

void MotorStart(void)
{
    ucT2state = STATERUN; 
	SFR_PAGE(_t2_0, noSST);        // switch to page 0
	T2_T2MOD  	=  0x1C;  									//3.25mS
	                           
	if(g_speed_start_ref > g_speed_end_ref)                  
    {
    	g_speed_start_ref = g_speed_end_ref;				   // Ensure that 'start_ref' never exceeds 'end_ref'.
    }        
    g_speed_ref        = g_speed_start_ref;
	
	ControlInit();
	CommInit();
 	gb_Off	=	0;
 	gb_On   = 	1; 
	gb_time_out		=	0;
  	gb_ctrap 		=	0;
	gb_hs_error		=	0;
    gb_overcurrent	=	0;
	//Enable inverter
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.PortPinOFF@;
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.PortPinON@;
	#endif
	bitTimeout=0;
	#if DAVECG_ControlPanelKBS.POT_ENABLE
	TR2=0;
	#endif
	Ramp_Scheduler=1;
	
}

 void ControlInit(void) 
{
    int counter = 0;

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

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

	g_duty_cyc	     = PULSE_PERIOD;                      
    

	g_pi_array.intg_buffer.S_long = 0;
 	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
															// interrupt immediately.
                        
	SFR_PAGE(_cc0, noSST);         						  
    CCU6_CC63SRLH  = PULSE_PERIOD;					 
															// 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)
{
	// Disable inverter
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.PortPinON@;
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.PortPinOFF@;
	#endif
	bitTimeout=0;
	ucT2state = STATEIDLE;
	SFR_PAGE(_t2_0, noSST);        // switch to page 0
	T2_T2MOD  	=  0x14;  									//200uS
	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.														
                                    
    CCU6_TCTR4L = 0x00;									   // CCU6 timer control register 4 
    CCU6_TCTR4H = 0x40;                                    // Shadow Tranfers by T13 Zero-Match    
        
     
 	gb_Off	=	1;
 	gb_On   = 	0; 
	#if DAVECG_ControlPanelKBS.POT_ENABLE
	TR2=1;
	#endif

	g_current=0;
	g_speed_CC60=0;
	g_hall_counter=0;	
	g_speed_ref   =0;
 }

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.
	
}
  #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 INIT_PI_VAR(void) 
{
    g_pi_array.ymax  = PIC_SPEED_YMAX;						    // Initialise the PI upper limit variable. 
    g_pi_array.ymin  = PIC_SPEED_YMIN;							// Initialise the PI lower limit variable. 
    speed_kp    = INIT_SPEED_KP;								// Initialise the PI proportional gain variable. 
    speed_ki    = INIT_SPEED_KI;								// Initialise the PI integral gain variable. 
}

void Rampup()
{
	if(Ramp_Scheduler>=Rampup_Counter)	 
	{
	if(g_speed_end_ref > g_speed_ref)						// End ref not reached?
	{                                                      
		g_speed_ref += 1;									// then increment.                     
	}                                                                                 
	if(g_speed_end_ref < g_speed_ref)						// actual ref greater than end ref?
	{                                                                         
		g_speed_ref -= 1;									// then decrement.  
	}
 	Ramp_Scheduler=1;
	}
	else
	Ramp_Scheduler++;
 }	

#if DAVECG_ControlPanelKBS.POT_ENABLE
 void Read_Speed(void)
{
	SFR_PAGE(_ad2, noSST);
	if(ADC_RESR1L & 0x10)
	{	
	   	SFR_PAGE(_ad2, noSST);
	 	speed_adc_H=ADC_RESR1H;
	 	speed_adc_L=ADC_RESR1L&0xC0;
	 	if((speed_adc_buf_L!=speed_adc_L)||(speed_adc_buf_H!=speed_adc_H))
		{
		 	speed_adc_buf_L=speed_adc_L;
	 		speed_adc_buf_H=speed_adc_H;
	 		SYSCON0	|= 0x01;
			//-------------------------------
			MDU_MR0 = speed_adc_L;
			MDU_MR1 = speed_adc_H;

			MDU_MD4 = SPEED_POT_SCALE_L;
			MDU_MD5 = SPEED_POT_SCALE_H;
			while(MDU_BSY==1);
								
			MDU_MDUSTAT &= 0x04;
			MDU_MDUCON   = 0x10;		
			while((MDU_MDUSTAT & 0x01) == 0);
			Speed_Ref_POT =(MDU_MR3<<8)+MDU_MR2;
				
			//-------------------------------
			SYSCON0 &= 0xfe;	
	 	
	 		if(Speed_Ref_POT>SPEED_MAX_TARGET)
		   		Speed_Ref_POT=SPEED_MAX_TARGET;
	
		   	g_speed_end_ref=Speed_Ref_POT;
			
		}
								 
				
	}
}
#endif 
#endif 