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


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


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

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

#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 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 	at 0x0020	unsigned char 	Status_word; 

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

  extern data 	at 0x2E 	unsigned int 	g_direction;							   // Index-offset for reading the switching pattern, as per specified motor direction.
  extern data 	at 0x2C 	int 			g_current;
  extern idata 	at 0x90 	unsigned int  	g_speed_CC60;
  extern xdata				int				task_counter;
  extern bit								bitTimeout;
   #if DAVECG_ControlAlgoKBS.CP_ENABLE
  extern xdata				unsigned char	UART_Tx0[5];
  extern xdata				unsigned char	UART_Tx1[6];
	
  extern char								RI_Count;
  extern bit								bituartRI;
	#endif
//****************************************************************************
// @Global Variables
//****************************************************************************
  data		unsigned int 	g_nv_ref;
  xdata 	int 			Ramp_Scheduler;

  //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;
  data		unsigned int 	time_measurement;
  data 		unsigned char 	exp_hp,curr_hp;
#endif

#if DAVECG_ControlAlgoKBS.KEIL
//****************************************************************************
// @Imported Global Variables
//****************************************************************************
  extern data 	unsigned int	g_nv_start_ref;	
  extern idata 	unsigned int 	g_nv_end_ref; 		
  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 xdata	int				task_counter;
  extern data  	unsigned int 	g_direction;	
  extern data  	int 			g_current;
  extern idata 	unsigned int  	g_speed_CC60;
  extern bit					bitTimeout;  
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  extern xdata	unsigned char	UART_Tx0[5];
  extern xdata	unsigned char	UART_Tx1[6];
  extern		char			RI_Count;
  extern bit					bituartRI;
 #endif
//****************************************************************************
// @Global Variables
//****************************************************************************
  idata		unsigned int 	g_nv_ref;
  xdata 	int 			Ramp_Scheduler;

  //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;
  data		unsigned int 	time_measurement;
  data 		unsigned char 	exp_hp,curr_hp;
  #endif
//****************************************************************************
// @External Prototypes
//****************************************************************************

 //****************************************************************************
// @Prototypes Of Local Functions
//****************************************************************************
  
  void MotorControl_vInit( void );
  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
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  void UARTInitVar(void);
  #endif
//****************************************************************************

void MotorControl_vInit( void )
{
  #if DAVECG_DriveKBS.InvActiveLow
  DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_ON;  										// disable inverter 
  #endif
  #if DAVECG_DriveKBS.InvActiveHigh
  DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_OFF;  										// disable inverter 
  #endif
	CPInitVar();
	#if DAVECG_ControlAlgoKBS.CP_ENABLE
	UARTInitVar();	
    RI_Count=0;
  	bituartRI=0;
	#else
	MotorStart();
	#endif
} // End of function MotorControl_vInit();

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

#if DAVECG_ControlAlgoKBS.CP_ENABLE
void UARTInitVar(void)
{
	//statusword /display variable
	#if DAVECG_ControlAlgoKBS.SDCC
	UART_Tx0[0]	= (unsigned char)&Status_word;
    UART_Tx0[1]	= (unsigned char)&g_speed_CC60+1;
   	UART_Tx0[2]	= (unsigned char)&g_speed_CC60;
	UART_Tx0[3]	= (unsigned char)&g_current+1;
	UART_Tx0[4]	= (unsigned char)&g_current;
	#endif
	#if DAVECG_ControlAlgoKBS.KEIL
	UART_Tx0[0]	= (unsigned char)&Status_word;
    UART_Tx0[1]	= (unsigned char)&g_speed_CC60;
   	UART_Tx0[2]	= (unsigned char)&g_speed_CC60+1;
	UART_Tx0[3]	= (unsigned char)&g_current;
	UART_Tx0[4]	= (unsigned char)&g_current+1;
	#endif

    //Graph DATA
	UART_Tx1[0]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar0@;
    UART_Tx1[1]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar1@;
    UART_Tx1[2]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar2@;
   	UART_Tx1[3]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar3@;
	UART_Tx1[4]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar4@;
	UART_Tx1[5]	= (unsigned char)&DAVECG_ControlAlgoKBS.CANMsgVar5@;
}
#endif

void MotorStart(void)
{
  	Status_word	= 0;  //Reset Ctrap, Timeout, overcurrent, wronghall
 	gb_On		= 1; 
	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();
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_OFF;  										// Enable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_ON;  										// Enable inverter 
	#endif
	bitTimeout=0;
	TR2 = 0; //   stop timer

}

 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;                      
    
	task_counter	= 0;								   // task '0' selected as default.
 	g_i_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
	
	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.InvActiveLow
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_ON;  										// disable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_OFF;  										// disable inverter 
	#endif
	TR2 = 1; //   start timer
	bitTimeout=0;
	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;
    unsigned long l_speed_cal = 0;

	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 = SPEED_CONSTANT ;                     // Load constant value in l_speed_cal.  
    }                                                      
    else												   // if motor has passed ramp up stage....
    {					                                   // then the accumulator has sufficient samples.
        if((int)((long)g_speed_acumm >> 16)  > 0)		   // accumulated time too big a number?.i.e motor speed too high?
        {
		    l_time = g_speed_acumm >> (SPEED_TIME_DIV);    // then scale it down to a smaller number.
		    l_speed_cal = SPEED_CONSTANT_AV;               // Load the division factor to calculate motor speed.  
        }
		else
		{												   // so accumulated time not a big number...i.e motor speed not that high.....
		    l_time = g_speed_acumm;                        // hence do not scale it down so that no precision loss.
		    l_speed_cal = SPEED_CONSTANT_AV_FACTOR;        // Load the division factor to calculate motor speed.  
		}
    }
    g_circ_index++;                                        // Increment index for circular buffer
    if(g_circ_index > INDEX_LIMIT)						   // end of circular buffer reached ?
    {
        g_circ_index = 0;                                  // then reset the Index of the buffer to '0'.
    }

    return (l_speed_cal / l_time);                         // finally compute motor speed.
	
}
#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.
        }
    }
}
										// Increment the s/w time base which determines the rate of dutycycle increment.
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=0;
	}
	else
		Ramp_Scheduler++;


  }


