//////////////////////////////////////////////////////////////////////
//********************************************************************
//********************		SCCH 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_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 0x002A 	unsigned int 	current_kp;
 extern idata	at 0x0096 	unsigned int 	current_ki;		


  //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 	at 0x0020	unsigned char 	Status_word; 
  extern idata 	at 0x8E		int   		    Rampup_Counter;
  extern data 				signed int 		pierror;
  extern data  				unsigned int 	g_pi_controller_speed_out;

  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
//****************************************************************************
  
  //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;
  xdata pi_con  		g_pi_speed_array;
  xdata pi_con  		g_pi_current_array;	
  data 	unsigned char 	exp_hp,curr_hp;
  data	unsigned int	g_speed_ref;
  xdata int 			Ramp_Scheduler;
  #if DAVECG_ControlPanelKBS.POT_ENABLE
  data	int				Speed_Ref_ADC;
  data	int				Speed_Buf_ADC;
		long_int		Speed_Temp_ADC;
 #endif
#endif //End of SDCC
#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;
 extern data	unsigned int	current_kp;
 extern idata	unsigned int 	current_ki;		

 //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 data 	signed int 		pierror;
 extern data  	unsigned int 	g_pi_controller_speed_out;

 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
//****************************************************************************
  
  //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;
 xdata	pi_con  		g_pi_speed_array;
 xdata	pi_con  		g_pi_current_array;	
 data 	unsigned char 	exp_hp,curr_hp;
 idata	unsigned int	g_speed_ref;
 xdata 	int 			Ramp_Scheduler;
#if DAVECG_ControlPanelKBS.POT_ENABLE
 data	int				Speed_Ref_ADC;
 data	int				Speed_Buf_ADC;
		long_int		Speed_Temp_ADC;
#endif
#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);
  int  SpeedCalculation();
  void OverCurrentCheck(void);
  void INIT_PI_VAR(void);
  void Current_Measurement(void);
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  void UARTInitVar(void);
  #endif
  #if DAVECG_ControlPanelKBS.POT_ENABLE
  void Read_Speed(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();
	INIT_PI_VAR();
	#if DAVECG_ControlAlgoKBS.CP_ENABLE
	UARTInitVar();	
	RI_Count=0;
	bituartRI=0;
	#else
	MotorStart();
	#endif
 
} // End of function MotorControl_vInit();


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;
	Rampup_Counter =SPEED_RAMPUP_COUNT;
	Status_word=1;
	g_speed_CC60=0;
}

#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_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();
	bitTimeout=0;
	#if DAVECG_ControlPanelKBS.POT_ENABLE
	TR2 = 1; //   stop timer
	#else
  	TR2 = 0; //   stop timer
	#endif
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_OFF;  										// Enable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.EnInvPortPin@ = ENABLE_ON;  										// Enable inverter 
	#endif
}

 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_pi_speed_array.intg_buffer = 0;
	g_pi_current_array.intg_buffer = 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)
{
	#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_CC63SRL	= PULSE_PERIOD;                          // Re-initialise shadow register channel 3 with 'PULSE_PERIOD'
	CCU6_CC63SRH	= PULSE_PERIOD>>8; 													   // 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_speed_ref		= 0;
 }

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.
	
}
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 INIT_PI_VAR(void) 
{
    g_pi_speed_array.ymax  = PIC_SPEED_YMAX;						   // Initialise the PI upper limit variable. 
    g_pi_speed_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. 
    g_pi_current_array.ymax  = PIC_CURRENT_YMAX;						   // Initialise the PI upper limit variable. 
    g_pi_current_array.ymin  = PIC_CURRENT_YMIN;						   // Initialise the PI lower limit variable. 
    current_kp    = INIT_CURRENT_KP;					   // Initialise the PI proportional gain variable. 
    current_ki    = INIT_CURRENT_KI;					   // Initialise the PI integral gain variable. 
}
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(); 
}
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=0;
	}
	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_Ref_ADC =((int)ADC_RESR1H<<8)+(ADC_RESR1L&0xC0);

		if(Speed_Ref_ADC!=Speed_Buf_ADC)
		{
		 Speed_Buf_ADC=Speed_Ref_ADC;
		 Speed_Temp_ADC.U_long=(long)Speed_Buf_ADC&0x0000ffff;
		 Speed_Temp_ADC.U_long=	Speed_Temp_ADC.U_long*SPEED_MAX_TARGET;
		
		#if DAVECG_ControlAlgoKBS.KEIL
		if(Speed_Temp_ADC.st.pr1>SPEED_MAX_TARGET)
		  Speed_Temp_ADC.st.pr1=SPEED_MAX_TARGET;
		g_speed_end_ref= Speed_Temp_ADC.st.pr1;
		#endif
		#if DAVECG_ControlAlgoKBS.SDCC
		if(Speed_Temp_ADC.st.pr0>SPEED_MAX_TARGET)
		  Speed_Temp_ADC.st.pr0=SPEED_MAX_TARGET;
		g_speed_end_ref= Speed_Temp_ADC.st.pr0;
		#endif
		 		 
		}
  }
 }
#endif
