//////////////////////////////////////////////////////////////////////
//********************************************************************
//******************	BC CCH Functions		**********************
//********************************************************************
//////////////////////////////////////////////////////////////////////


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


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

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

//****************************************************************************
// @Imported Global Variables
//****************************************************************************
   //control Parameter
  extern  	C_BDATA			Status_word; 
  extern 	bit				gb_overcurrent;
  extern 	bit 			gb_Closeloop ;
  extern 	bit 			gb_ctrap;
  extern 	bit	 			gb_time_out;
  extern 	bit 			gb_On;
  extern 	bit 			gb_Off;
  extern 	bit 			gb_Ramp;
  extern 	const 	uword 	Close_Patt[];
  extern 	const 	uword 	Open_Patt[];
  #if DAVECG_ControlAlgoKBS.KEIL
  extern 	 cCCH C_SDATA	cCCH0;
  #endif  //end of keil
  #if DAVECG_ControlAlgoKBS.Tasking
  extern 	 cCCH 			cCCH0;	
  #endif //end of Tasking
  //****************************************************************************
// @Global Variables
//****************************************************************************
  bit 					bitNewCMD0=0;
  bit					bitTimeout;

  uword 	C_SDATA		g_speed_buffer[6*PP];
	
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  uword 	C_SDATA		CANTrxBuf0[4];
  uword 	C_SDATA		CANTrxBuf1[4];
  #endif
    ubyte 	C_SDATA		Curr_HP;
  uword 	C_SDATA 	Current_Ref;
  uword		C_SDATA 	Ramp_Counter;

  //Bemf Parameter
  
 
//****************************************************************************
// @External Prototypes
//****************************************************************************
 #if DAVECG_ControlAlgoKBS.CP_ENABLE
 extern void CAN_Transmit_MO1(void);
 #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);
  void Ramp(void);
  void Commutation(void);
  #if DAVECG_ControlAlgoKBS.SPEED_CALCU
  int SpeedCalculation(void);
  #endif
  void PIInitVar(void);
  void Current_Rampup(void);
//****************************************************************************
#if DAVECG_ControlAlgoKBS.CP_ENABLE
void CANInitVar(void)
{
  // Status Word, Speed data
  CANTrxBuf0[0] = (unsigned int) &Status_word;					
  CANTrxBuf0[1] = (unsigned int) &cCCH0.Motor_Current;					
  CANTrxBuf0[2] = (unsigned int) &cCCH0.Motor_Speed;					
  CANTrxBuf0[3] = (unsigned int) &cCCH0.Motor_Current;
 
  // Graph Data
  CANTrxBuf1[0] = (unsigned int) &DAVECG_ControlAlgoKBS.CANMsgVar0@;					
  CANTrxBuf1[1] = (unsigned int) &DAVECG_ControlAlgoKBS.CANMsgVar1@;					
  CANTrxBuf1[2] = (unsigned int) &DAVECG_ControlAlgoKBS.CANMsgVar2@;					
  CANTrxBuf1[3] = (unsigned int) &cCCH0.Motor_Speed;
  bitNewCMD0 	= 0;
}
#endif
void CPInitVar(void)
{		
	cCCH0.Motor_Direction	= MOTOR_DIRECTION * DIRECTION_SCALE;			  
	cCCH0.Current_Ref  		= MOTOR_CURRENT_REF;
	cCCH0.Motor_Speed		= 0;
	Status_word				= 1;  				
}

void MotorControl_vInit( void )
{
  #if DAVECG_DriveKBS.InvActiveLow
  DAVECG_DriveKBS.InvPortPin@ = ENABLE_ON;  										// disable inverter 
  #endif
  #if DAVECG_DriveKBS.InvActiveHigh
  DAVECG_DriveKBS.InvPortPin@ = ENABLE_OFF;  										// disable inverter 
  #endif	
  CPInitVar();
  PIInitVar();
  #if DAVECG_ControlAlgoKBS.CP_ENABLE
  CANInitVar();
  CAN_Transmit_MO1();
  #else
  MotorStart();
  #endif

} // End of function MotorControl_vInit();

void ControlInit(void) 
{
    int counter = 0;

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

    cCCH0.Speed_Acumm   = 0x00000008;						   
    cCCH0.Circ_Index    = 0x0000;                   
    cCCH0.Speed_Counter	= 0x0000;

 	cCCH0.Ramp_Scheduler = 1;
	cCCH0.Motor_Speed	= 0;
	cCCH0.Current.Ibuf	= 0;
	Current_Ref			= 200;
	Ramp_Counter		= 0;

} 

void CommInit(void)
{
    CCU60_MCMCTR 	= 0x0000;             						// CCU6 multi channel mode control
   	CCU60_CC61SR 	= 10;
	CCU60_CC62SR  	= CCU60_CC61SR + T13_TIME;				// 32 = T13_TIME;
    CCU60_T12     	= T13_TIME + 15;						// larger value so that it doesn't generate any
	
	cCCH0.Duty_Cyc 	= PULSE_PERIOD-200;			
	
	if (cCCH0.Duty_Cyc < DUTY_CYCLE_MIN) 			 
		cCCH0.Duty_Cyc	= DUTY_CYCLE_MIN;				
	else if(cCCH0.Duty_Cyc > DUTY_CYCLE_MAX)
		cCCH0.Duty_Cyc	= DUTY_CYCLE_MAX;		
	                    
	CCU60_CC63SR 	= cCCH0.Duty_Cyc;								// to zero % duty cycle.

    CCU60_TCTR4   	= 0x4040;								   // select the events to trigger shadow transfers of T12 & T13.

	   
	Curr_HP			= (ubyte)((P10_IN >> 7) & 0x0007);				   // read Hall Pins on startup.

	CCU60_MCMOUTS	= Open_Patt[Curr_HP+cCCH0.Motor_Direction]|0x8080;

	CCU60_MCMOUTS	= Close_Patt[Curr_HP+cCCH0.Motor_Direction];
		
      
    CCU60_TCTR4   	= 0x0600;									// T13 Reset/Run --> Start PWM 
  
    CCU60_MCMCTR    = 0x0014;									// Trigger Shadow Tranfers at correct hall
															// event, synchronized to T13 Zero-Match
	CCU60_TRPCTR	|= 0x8000;
        			
    CCU60_TCTR4    	 = 0x0002;									// T12 Run

 }


void MotorStart(void)
{
 	Status_word		= 0;										//Reset Ctrap, Timeout, overcurrent, wronghall
 	gb_On   		= 1; 
    bitTimeout		= 0;                        

	
	ControlInit();
	CommInit();
	 #if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.InvPortPin@ = ENABLE_OFF;  										// Enable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.InvPortPin@ = ENABLE_ON;  										// Enable inverter 
	#endif
	#if DAVECG_ControlAlgoKBS.CP_ENABLE
	CAN_Transmit_MO1();
	#endif
}
 
void MotorStop(void)
{
	#if DAVECG_DriveKBS.InvActiveLow
	DAVECG_DriveKBS.InvPortPin@ = ENABLE_ON;  										// disable inverter 
	#endif
	#if DAVECG_DriveKBS.InvActiveHigh
	DAVECG_DriveKBS.InvPortPin@ = ENABLE_OFF;  										// disable inverter 
	#endif
	gb_Ramp				= 0;
   	CCU60_MCMCTR 		= 0x0000;							// CCU6 multi channel mode control        
															// Enable Shadow Tranfers direct mode
   	CCU60_MCMOUTS 		= 0x8080;							// All Transistors OFF
	CCU60_TCTR4 		= 0x0505;							// CCU6 timer control register 4
   															// T13/T12 Reset, T13/T12 Stop -->  No PWM active 
    CCU60_CC63SR 		= 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.														
    CCU60_TCTR4 		= 0x4000;							// CCU6 timer control register 4 
    														// Shadow Tranfers by T13 Zero-Match    
 	gb_Off				= 1;
 	gb_On   			= 0; 
	gb_Closeloop		= 0;

	cCCH0.Motor_Current	= 0;
	cCCH0.Speed_Counter	= 0;	
	cCCH0.Motor_Speed	= 0;
	#if DAVECG_ControlAlgoKBS.CP_ENABLE
	CAN_Transmit_MO1();
	#endif
 }
#if DAVECG_ControlAlgoKBS.SPEED_CALCU


int SpeedCalculation()   
{
    unsigned int  l_time ;
    long  l_speed_cal;
	
	cCCH0.Speed_Acumm  += cCCH0.Time_Measure;						// Accumulate the new sample i.e measured time
															// into a Moving Average Accumulator.
    cCCH0.Speed_Acumm  -= g_speed_buffer[cCCH0.Circ_Index];			// Subtract out the oldest sample from the Accumulator.       

    g_speed_buffer[cCCH0.Circ_Index] = cCCH0.Time_Measure;			// Preserve the latest sample so that it can be subtracted
															// out when required.
    if(cCCH0.Speed_Counter < PP_FACTOR)							// motor still in ramp up stage?
    {
        cCCH0.Speed_Counter = cCCH0.Speed_Counter + 1;		// then Moving Average Accumulator still hasn't sufficient samples.
        l_time 				= cCCH0.Time_Measure;					// 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)cCCH0.Speed_Acumm >> 16)  > 0)			// accumulated time too big a number?.i.e motor speed too high?
        {
		    l_time 		= (int)(cCCH0.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 		= (int)cCCH0.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.  
		}
    }
	cCCH0.Circ_Index++;
															// Increment index for circular buffer
    if(cCCH0.Circ_Index > INDEX_LIMIT)							// end of circular buffer reached ?
    {
        cCCH0.Circ_Index = 0;									// then reset the Index of the buffer to '0'.
    }
	return (l_speed_cal / l_time);							// finally compute motor speed.
}
#endif
void PIInitVar(void)
{
 	cCCH0.Current.Kp		= DEFAULT_CURRENT_KP;
	cCCH0.Current.Ki		= DEFAULT_CURRENT_KI;
	cCCH0.Current.Ymin	= PIC_CURRENT_YMIN;
	cCCH0.Current.Ymax	= PIC_CURRENT_YMAX;
}
void Current_Rampup(void)
{
	if(Ramp_Counter<1)
	{
		if(Current_Ref<cCCH0.Current_Ref)
			Current_Ref++;
		else if(Current_Ref>cCCH0.Current_Ref)
			Current_Ref--;
		Ramp_Counter=10;
	}
	Ramp_Counter--;
}	

