//////////////////////////////////////////////////////////////////////
//********************************************************************
//******************	BC SCH 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 	 cSCH C_SDATA	cSCH0;
  #endif  //end of keil
  #if DAVECG_ControlAlgoKBS.Tasking
  extern 	 cSCH 			cSCH0;	
  #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;
	

  //Bemf Parameter
  
 
//****************************************************************************
// @External Prototypes
//****************************************************************************
 #if DAVECG_ControlAlgoKBS.CP_ENABLE
 extern void CAN_Transmit_MO1(void);
 #endif
 #if DAVECG_ControlPanelKBS.POT_ENABLE
 extern unsigned int MUL_MAC(unsigned int a, unsigned int b);
 #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);
  int SpeedCalculation(void);
  void PIInitVar(void);
  #if DAVECG_ControlPanelKBS.POT_ENABLE
  void Read_Speed(void);
  #endif
//****************************************************************************
#if DAVECG_ControlAlgoKBS.CP_ENABLE
void CANInitVar(void)
{
  // Status Word, Speed data
  CANTrxBuf0[0] = (unsigned int) &Status_word;					
  CANTrxBuf0[1] = (unsigned int) &cSCH0.Motor_Current;					
  CANTrxBuf0[2] = (unsigned int) &cSCH0.Motor_Speed;					
  CANTrxBuf0[3] = (unsigned int) &cSCH0.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) &cSCH0.Motor_Speed;
  bitNewCMD0 	= 0;
}
#endif
void CPInitVar(void)
{		
	cSCH0.Speed_End_Ref		= MOTOR_END_REF;					   
	cSCH0.Speed_Start_Ref	= MOTOR_START_REF;				  
	cSCH0.Motor_Direction	= MOTOR_DIRECTION * DIRECTION_SCALE;			  
	cSCH0.Speed_Ref   		= 0;
	cSCH0.Rampup_Counter 	= SPEED_RAMPUP_COUNT;
	cSCH0.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;
    }

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

 	cSCH0.Ramp_Scheduler = 1;
	cSCH0.Motor_Speed	= 0;
	cSCH0.Speed.Ibuf=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
	
	cSCH0.Duty_Cyc 	= PULSE_PERIOD;			
	
	if (cSCH0.Duty_Cyc < DUTY_CYCLE_MIN) 			 
		cSCH0.Duty_Cyc	= DUTY_CYCLE_MIN;				
	else if(cSCH0.Duty_Cyc > DUTY_CYCLE_MAX)
		cSCH0.Duty_Cyc	= DUTY_CYCLE_MAX;		
	                    
	CCU60_CC63SR 	= cSCH0.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+cSCH0.Motor_Direction]|0x8080;

	CCU60_MCMOUTS	= Close_Patt[Curr_HP+cSCH0.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;                        

	if(cSCH0.Speed_Start_Ref > cSCH0.Speed_End_Ref)                  
    {
    	cSCH0.Speed_Start_Ref = cSCH0.Speed_End_Ref;				// Ensure that 'start_ref' never exceeds 'end_ref'.
    }        
    cSCH0.Speed_Ref	= cSCH0.Speed_Start_Ref;
	
	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;

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



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

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

void PIInitVar(void)
{
 	cSCH0.Speed.Kp		= DEFAULT_SPEED_KP;
	cSCH0.Speed.Ki		= DEFAULT_SPEED_KI;
	cSCH0.Speed.Ymin	= PIC_SPEED_YMIN;
	cSCH0.Speed.Ymax	= PIC_SPEED_YMAX;
}
#if DAVECG_ControlPanelKBS.POT_ENABLE
void Read_Speed(void)
{
	unsigned int POT_Value,POT_Speed;

	if(ADC0_VFR&0x0002)
	{
		POT_Value = (ADC0_RESR1)& 0x0FFF;

		POT_Speed  =MUL_MAC(POT_Value,SPEED_POT_SCALE);

		if(POT_Speed> SPEED_POT_SCALE)
   			POT_Speed= SPEED_POT_SCALE;

		cSCH0.Speed_End_Ref=POT_Speed;
	}
}
#endif
