//////////////////////////////////////////////////////////////////////
//********************************************************************
//********************		CCH 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_current_ref;
 extern idata 	at 0x0092  	unsigned int 	current_kp;
 extern idata 	at 0x0094  	unsigned int 	current_ki;

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

 extern data 				signed int 		pierror;
 extern data  				unsigned int 	g_pi_controller_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;
 xdata	int	 				g_i_counter;
 data	unsigned int 		time_measurement;
 xdata	pi_con  			g_pi_array;
 data 	unsigned char 		exp_hp,curr_hp;
#endif //End of SDCC
#if DAVECG_ControlAlgoKBS.KEIL
//****************************************************************************
// @Imported Global Variables
//****************************************************************************
 extern data	unsigned int 		g_current_ref;
 extern idata	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 data 	unsigned char 		Status_word; 

 extern data 	signed int 			pierror;
 extern data  	unsigned int 		g_pi_controller_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_array;
 data 	unsigned char 		exp_hp,curr_hp;
#endif //End of KEIL
//****************************************************************************
// @External Prototypes
//****************************************************************************

 extern  unsigned int PIControllerCurrent(long *buf_ptr,unsigned int reference,unsigned int act);
//****************************************************************************
// @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
 void OverCurrentCheck(void);
 void INIT_PI_VAR(void);
 void Current_Measurement(void);
 #if DAVECG_ControlAlgoKBS.CP_ENABLE
 void UARTInitVar(void);
 #endif
//****************************************************************************

void MotorControl_vInit( void )
{
	#if DAVECG_DriveKBS.ENABLE_INVERTER
	P0_3 =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)
{
	g_direction		= MOTOR_DIRECTION * DIRECTION_SCALE;			  
	g_current_ref   = MOTOR_CURRENT_REF;
   	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; 
	ControlInit();
	CommInit();
	#if DAVECG_DriveKBS.ENABLE_INVERTER
	P0_3 =ENABLE_ON;
	#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_pi_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;						   // Initialize channel3 shadow register with value corresponding
														  
	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
	P0_3=ENABLE_OFF;
	#endif
	TR2 = 1; //   start timer
	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;	
 }

#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
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_array.ymax  = PIC_CURRENT_YMAX;						   // Initialise the PI upper limit variable. 
    g_pi_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(); 
}
