//*****************************************************************************/
// @Module         Speed Control
// @Filename       SCH_CTRL.C
// @Controller     XC88x Series
//
//
// @Description    This file contains functions for Speed control through 
//                 Block Commutation
//*****************************************************************************/
//****************************************************************************
// @Includes
//****************************************************************************
#include "MAIN.H"
//****************************************************************************/
// @Imported Global Variables
//****************************************************************************/


extern unsigned char const open_loop[];
extern unsigned char const closed_loop[];
extern unsigned char const exp_hall_patt[];

#if DAVECG_CONTROL_PANEL_ENABLE
extern bit gb_motor_status;								   // bit variable which reflects/controls motor start/stop status.
extern C_BDATA g_trigger_status;						   // bit variable which triggers sampling/capture of graph variable.
#else
C_UBDATA g_trigger_status;                                 // trigger status word
C_SBIT gb_motor_status		C_ATBIT(g_trigger_status, 5);  // motor status flag
#endif
//****************************************************************************/
// @Local Function Prototypes
//****************************************************************************/
void motor_start(void);
void motor_stop(void);

void comm_init(void);
int speed_calculation(unsigned int time_measurement, U_CHAR *speed_counter, int limit);
void init_control(void);
void motor_ramp_generation(void);
unsigned int pi_controller_16bit(long *buf_ptr,reference,act);
#if DAVECG_CURRENT_SENSE
void OVER_CURRENT_CHECK(void);
#endif
//****************************************************************************
// @Imported Function Prototypes
//****************************************************************************


//****************************************************************************
// @Global Variables
//****************************************************************************
unsigned char exp_hp,curr_hp,curr_exp_hp;

C_BDATA g_status_word;
unsigned char g_once;
int C_SDATA g_i_counter;								   // s/w counter to specify the time limit for motor 'Over Current'.
unsigned char g_direction;								   // Index-offset for reading the switching pattern, as per specified motor direction.
C_UBDATA  g_direction_user;								   // variable to specify the desired motor direction.
unsigned int idata g_current;
C_UBDATA g_trap_reset;									   // set this variable to '1', to reset the 'Latched CTRAP' condition.
int C_SDATA g_increment_free;
unsigned int idata g_pi_controller_out;

int C_SDATA g_counter0;									   // s/w time base used in motor start-up in BEMF mode.
unsigned int idata g_duty_cyc;
unsigned int idata g_speed_setref;
unsigned int idata g_nv_end_ref;
unsigned int idata g_nv_start_ref;
unsigned int C_SDATA g_nv_start_ref0;
unsigned char g_circ_index;								   // Index to access the circular buffer used in motor speed computation.
unsigned int g_speed_buffer[6*PP];						   // s/w array(memory) for preserving the previous samples of motor speed.
unsigned long C_SDATA g_time_step;
unsigned long C_SDATA g_counter1;
unsigned long g_speed_acumm;							   // s/w accumulator for averaging of motor speed.
unsigned long idata g_ramp_up_time;
int idata g_speed_counter;
U_CHAR task_counter;

// Declaration of bit-variables required to store motor status.
C_SBIT gb_on           C_ATBIT(g_status_word, 8);          // ON                           
C_SBIT gb_off          C_ATBIT(g_status_word, 9);          // OFF                           
C_SBIT gb_idle_state   C_ATBIT(g_status_word, 10);         // Idle_state
C_SBIT gb_hs_error     C_ATBIT(g_status_word, 11);         // Wrong hall event          
C_SBIT gb_time_out     C_ATBIT(g_status_word, 12);         // Time_out detection
C_SBIT gb_ctrap        C_ATBIT(g_status_word, 13);         // Ctrap detection
C_SBIT gb_overcurrent  C_ATBIT(g_status_word, 14);         // Overcurrent detection
 



unsigned char g_hall_counter;
unsigned int idata g_speed_CC60;
int idata g_test_kp;									   // variable to hold user specified PI proportional Gain.        
int idata g_test_ki;									   // variable to hold user specified PI integral Gain.            
int idata  g_test_ymax;									   // variable to hold user specified PI saturation upper limit.   
int idata  g_test_ymin;									   // variable to hold user specified PI saturation lower limit.   


pi_con idata g_pi_array;

#define CONDITION_OPERATOR <
#define SPEED_CONSTANT_AV_FACTOR	(SPEED_CONSTANT_AV * 8) 
#define INDEX_LIMIT	((6*PP) -1)
//****************************************************************************
// @Function        void motor_start(void)
// Description		This Function executes the functions required for Motor
//					start-up such as initialization of motor related variables,
//					initialization of motor related SFRs etc.
//					It also ensures that 'motor_start_ref' is always lesser
//					than the 'motor_end_ref'.
//----------------------------------------------------------------------------
void motor_start(void)
{
	if (g_once == 0x0)
	{
		g_trap_reset = 1;
		g_once = 0x01;
        g_status_word = 0x0001;                            // Set 'gb_on' flag to convey to the user that 'motor_start' command is issued.
        if(g_nv_start_ref > g_nv_end_ref)                  // Start reference limitation
        {
            g_nv_start_ref = g_nv_end_ref;				   // Ensure that 'start_ref' never exceeds 'end_ref'.
        }        
        g_nv_start_ref0		= g_nv_start_ref;              // make another copy of start voltage reference.
        g_speed_setref      = g_nv_start_ref;              // Set start voltage reference into actual voltage reference.           
		init_control();                                    // initialisation of all the variables required for motor start up.
		comm_init();
		g_duty_cyc = DUTY_CYCLE_MIN;

	}
} // motor_start
//****************************************************************************
// @Function        void motor_stop(void)
// Description		This function implements the functions required for motor
//					stop such as switching off the PWM, all MOSFETs, stopping
//					all timers etc.
//----------------------------------------------------------------------------
void motor_stop(void)
{
	SFR_PAGE(_cc2, noSST);         						   // switch to page 2
    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;		                   // Re-initialise shadow register channel 3 with 'PULSE_PERIOD'
														   // 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    
        
   
    if(gb_motor_status == 1)							   // if motor stop command detected, clear g_once so that it executes                                      
    {                                                      // motor start function when user issues start command.
        g_once = 0x00;                                     
    }
	
	gb_off	= 1;                                           // Status update
    gb_on	= 0;                                           // Status update

	
 } // motor_stop
//****************************************************************************
// @Function        void commutation_init(void)
// Description		This function initialises the SFRs required for motor start-up
//					such as loading of the Modulation register, enabling of the Timers,
//					enabling of the Interrupts etc.
//----------------------------------------------------------------------------
void comm_init(void)
{
//****************************************************************************
	SFR_PAGE(_cc2, noSST);         						   // switch to page 0
    CCU6_MCMCTR = 0x0000;               				   // 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 0
    CCU6_T12LH     = CCU6_CC62SRLH + 1;					   // Initialize T12 timer with a sufficiently 
														   // larger value so that it doesn't generate any
														   // interrupt immediately.
                        
	SFR_PAGE(_cc0, noSST);         						   // switch to page 0
    CCU6_CC63SRLH  = PULSE_PERIOD;					       // 0x4af = PULSE_PERIOD;   
														   // Initialize channel3 shadow register with value corresponding
														   // to zero % duty cycle.
                                                                     
    CCU6_TCTR4L   = 0x40;								   // select the events to trigger shadow transfers of T12 & T13.
    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 2
    CCU6_MCMCTR  = 0x0014;								   // Trigger Shadow Tranfers at correct hall
														   // event, synchronized to T13 Zero-Match
	#if DAVECG_ENABLE_TRAP
	CCU6_TRPCTRH	|=	0x80;							   // Enable TRAP interrupt.
	#endif	//TRAP
	SFR_PAGE(_cc0, noSST);         						   // switch to page 0
    CCU6_TCTR4L   = 0x02;								   // T12 Run
	CCU6_TCTR4H	  = 0x00;
//------------------------------------------------------------------------------------
}
//****************************************************************************
// @Function        void init_control(void)
// Description		This function initialises the various variables required 
//					for motor start up.
//----------------------------------------------------------------------------

void init_control(void) 
{
    
    int l_i = 0;

    for(l_i = 0;l_i < (6 * PP);l_i++)
    {
        g_speed_buffer[l_i] = 0;
    }
    g_speed_acumm    = 0x00000008;						   // initialise speed accumulator with
														   // 8 so that division by 8 won't result in zero.
    g_circ_index     = 0x0000;                   
    g_speed_counter  = 0x0000;
    g_speed_CC60     = 0x0000;
    g_hall_counter   = 0x0000;

		
    g_counter1       = 0x00000000;
    g_time_step      = 0x00000000;
    g_duty_cyc	     = PULSE_PERIOD;                       // initialization of duty cycle
    
    g_i_counter		 = 0x0000;							   // s/w time base for over-current is cleared to '0'.
	g_direction		 = g_direction_user * 8;
	task_counter	 = 0;	
	g_pi_array.intg_buffer.S_long = 0;
    
}                                                          // End of function init_control
//****************************************************************************
// @Function        void motor_ramp_generation(void)
// Description		This function verifies whether the user has entered a new 
//					'end reference' and accordingly ramps up the duty cycle,
//					to reach the new 'end reference'
//----------------------------------------------------------------------------
void motor_ramp_generation(void)
{
    int l_ref_difference = 0;
    unsigned long l_co_instructions = 0;
	
        if(g_increment_free == 1)								// if the hardware timer interrupt has occured.
        {
          g_increment_free = 0;
          g_counter1 += 64;
        }

        if(g_counter1 >= g_time_step)							// if the 'timestep'(Delta) for ramping has elapsed.
		{
          //--------speed_ref_ramp-------------					// then inc/dec the reference voltage by one count...
			if(g_nv_end_ref > g_speed_setref)					// End ref not reached?
			{                                                                         
			g_speed_setref += 1;								// then increment.  
			}                                                                                 
			if(g_nv_end_ref < g_speed_setref)					// actual ref greater than end ref?
			{                                                                         
			g_speed_setref -= 1;								// then decrement.  
			}                                                                                 
		  //-----------------------------------
          g_counter1 = 0;										// and reset the 'timestep' s/w counter.
        }
		if(g_nv_start_ref0 != g_nv_end_ref)						// if the end reference i.e motor end speed has been
        {														// changed by the user.

		  l_ref_difference	= g_nv_end_ref - g_nv_start_ref0;
		  if(l_ref_difference < 0)
			{
			  l_ref_difference = -l_ref_difference;
			}

          g_time_step = g_ramp_up_time  / l_ref_difference;		// then calculate the 'time step' as per the new 
          g_nv_start_ref0 = g_nv_end_ref;						// 'difference in speed'
        }														// i.e g_time_step = g_ramp_up_time / l_ref_diff......
		 
}//  End of function motor_ramp_generation
//****************************************************************************
// @Function        void speed_calculation(void)
// Description		This function computes the actual motor speed from the
//					measured 'time between two Hall events'. It also implements
//					a moving average filter to suppress any invalid spikes from 
//					the Hall sensor.	
//----------------------------------------------------------------------------
int speed_calculation(unsigned int time_measurament, U_CHAR *speed_counter, int limit)   
{
 	#if DAVECG_SPEED_CALCU
   unsigned int  l_time = 0;
   unsigned long l_speed_cal = 0;

    g_speed_acumm  += time_measurament;					   // 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_measurament;       // Preserve the latest sample so that it can be subtracted
														   // out when required.
    if(*speed_counter < limit)							   // motor still in ramp up stage?
    {
        *speed_counter = *speed_counter + 1;			   // then Moving Average Accumulator still hasn't sufficient samples.
        l_time = time_measurament;						   // 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.
	#else
	return(0);											   // Speed Calculation feature has been disabled.
	#endif	//SPEED_CALCU

}                                                          // End of function speed_calculation 

//---------INLINE FUNCTIONS of CTRL.H begin--------------------------------------------------
//*************************************************************************************************
void CONTROL_PANEL_PARAMS(void);
void INIT_CTRL_VAR(void);
void MCU_INIT(void);
void CCU6_CTRL_REG(void);

#if DAVECG_CONTROL_PANEL_ENABLE
extern void trace(void);								   
#endif

//----------------------------------------------------------------
//*************************************************************************************************
#define		REQUESTED				1
#define		RESET					0
#define		MOTOR_READY_TO_START	0
#define		MOTOR_STOPPED			1
//*************************************************************************************************

//*************************************************************************************************
// @Function        void CONTROL_PANEL_PARAMS(void)     
// Description		This Function loads the values entered by the user in the 'Run Time Control Panel'
//					dialog of DID into the appropriate target variables. 
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
void CONTROL_PANEL_PARAMS(void)
{
    g_trap_reset	=	1;								   // set the 'trap_reset' s/w flag so that 
														   // s/w 'trap' flag is cleared under power ON.
    gb_ctrap		=	0;								   // clear the s/w trap flag to begin with.
	g_nv_end_ref	=	MOTOR_END_REF;					   // Initialise the end reference with GUI(user) value.
	g_nv_start_ref	=	MOTOR_START_REF;				   // Initialise the start reference with GUI(user) value.
	g_ramp_up_time	=	RAMP_UP_TIME;					   // Initialise the rampup time with GUI(user) value.
	g_direction_user=	MOTOR_DIRECTION;				   // Initialise the motor direction variables
	g_direction		=	g_direction_user * 8;			   // with GUI(user) specified direction.
	#if DAVECG_CONTROL_PANEL_ENABLE
	gb_motor_status	=	1;								   // set the motor_status flag if motor
														   // start not requested by GUI(user).
	#else
	gb_motor_status =	0;								   // clear the motor_status flag if motor
														   // start is requested by GUI(user).
	#endif
}
//*************************************************************************************************
// @Function        void INIT_PI_VAR(void)     
// Description		This function initialises the PI gain & Limit variables with the corresponding 
//					user entered values from the Run time control panel dialog of DID.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
INLINE void INIT_PI_VAR(void) 
{
    g_pi_array.ymax  = PIC_YMAX;						   // Initialise the PI upper limit variable. 
    g_pi_array.ymin  = PIC_YMIN;						   // Initialise the PI lower limit variable. 
    g_pi_array.kp    = INIT_SPEED_KP;					   // Initialise the PI proportional gain variable. 
    g_pi_array.ki    = INIT_SPEED_KI;					   // Initialise the PI integral gain variable. 
}

//*************************************************************************************************
// @Function        void INIT_CTRL_VAR(void)     
// Description		This function initialises the various intermediate variables that are required to 
//					be set to pre-defined default values before any motor related operation.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
//*************************************************************************************************
void INIT_CTRL_VAR(void)
{
	INIT_PI_VAR();										   // execute PI initialisation routine.
	CONTROL_PANEL_PARAMS();								   // execute control panel dependent variable initialisation routine.
}
//*************************************************************************************************
// @Function        void CCU6_CTRL_REG(void)     
// Description		This function initialises the various SFRs of the CC6 peripharal that are required  
//					to be set to pre-defined default values before any motor related operation.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
void CCU6_CTRL_REG(void)
{
/*  CCU6_T12DTC  =  CCU6_T12DTC_VAL; 
  CCU6_T13PR   =  PULSE_PERIOD; 
  CCU6_TCTR0   =  T12_CLOCK; 
  CCU6_T12PR   =  TIM_OUT; 
  CCU6_PSLR    =  PASSIVE_STATE; 
  CCU6_MODCTR  =  MOD_CONTROL; 
  CCU6_TRPCTR  =  0x3F07; 
  CCU6_TCTR2   =  0x0000;*/
}
//*************************************************************************************************
//*************************************************************************************************
// @Function        void MCU_INIT(void)     
// Description		This function initialises UART peripharal for desired baudrate. 
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
void MCU_INIT(void)
{
	#if DAVECG_CONTROL_PANEL_ENABLE
	sio_init();											   // Initialize the UART module.
	#endif
}
//*************************************************************************************************
#if DAVECG_CURRENT_SENSE
//*************************************************************************************************
//*************************************************************************************************
// @Function        void OVER_CURRENT_CHECK(void)     
// Description		This Function implements the logic required for 'over current' detection.
// Parameters		none
// Return value		none
//-------------------------------------------------------------------------------------------------
void OVER_CURRENT_CHECK(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;							   // Set the 'overcurrent' flag to convey 
														   // the same to the control panel
            motor_stop();								   // if yes, then stop the motor.
            gb_motor_status = 1;						   // Set the 'motor status' flag to convey 
														   // to the control panel that motor has been stopped.
           
        }
    }
    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.
        }
    }
}
#endif