//*****************************************************************************/
// @Module         Speed Current Control
// @Filename       SCCH_CTRL.C
// @Controller     XC16x Series
//
//
// @Description    This file contains functions for SpeedCurrent control through 
//                 Block Commutation
//*****************************************************************************/
//****************************************************************************
// @Includes
//****************************************************************************
#include "MAIN.H"

//****************************************************************************/
// @Imported Global Variables
//****************************************************************************/

#if DAVECG_TLE
extern int C_SDATA g_alt_sel0_P1L;
extern int C_SDATA g_alt_sel0_P1L_del;
#endif // TLE == 1


extern int const SP_St_Tab_r_l[];
extern int const SP_Tab_r_l[];

#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;								   // bit variable which triggers sampling/capture of graph variable. 
C_SBIT gb_motor_status C_ATBIT(g_trigger_status, 5);  	   // bit variable which reflects/controls motor start/stop status.
#endif

//****************************************************************************/
// @Local Function Prototypes
//****************************************************************************/

void motor_start(void);
void motor_stop(void);


void commutation_init(void);
int speed_calculation(unsigned int time_measurement, int *speed_counter, int limit);
void init_control(void);
void motor_ramp_generation(void);

#if DAVECG_CURRENT_SENSE
void adc_offset(void);
#endif // CURRENT_SENSE == 1




void speed_ref_ramp(void);
void blink_led(void);

//****************************************************************************
// @Imported Function Prototypes
//****************************************************************************

#if DAVECG_TLE
extern void driver_enable(void);
#endif // TLE == 1

//****************************************************************************
// @Global Variables
//****************************************************************************

C_BDATA g_status_word;
int C_SDATA g_current_max;
int C_SDATA g_once;										   // bit word containing all motor status bits.
int C_SDATA g_i_counter;								   // s/w counter to specify the time limit for motor 'Over Current'.
int C_SDATA g_direction;								   // Index-offset for reading the switching pattern, as per specified motor direction.
int C_SDATA g_direction_user;							   // variable to specify the desired motor direction.
int C_SDATA g_pic_speed_out;
int C_SDATA g_current;									   // variable which stores the 'motor current' information.
int C_SDATA g_trap_reset;								   // set this variable to '1', to reset the 'Latched CTRAP' condition.
int C_SDATA g_increment_free;							   // s/w flag to specify that T13 interrupt has occured.

int C_SDATA g_counter0;									   // s/w time base used in motor start-up in BEMF mode.
int C_SDATA g_pic_current_out;

unsigned int C_SDATA g_duty_cycle;						   // The desired PWM Duty Cycle is reflected in this variable.
unsigned int C_SDATA g_nv_end_ref;
unsigned int C_SDATA g_nv_start_ref;
unsigned int C_SDATA g_nv_start_ref0;
unsigned int C_SDATA g_circ_index;						   // Index to access the circular buffer used in motor speed computation.
unsigned int C_SDATA g_speed_buffer[6*PP];				   // s/w array(memory) for preserving the previous samples of motor speed.
unsigned int C_SDATA g_speed_ref;						   // variable to specify the desired 'motor speed'.

long C_SDATA g_adc_offset_res;							   // Computed ADC offset is stored in this variable.
long C_SDATA g_adc_offset_acumm;						   // s/w accumulator for averaging of ADC offset.

unsigned long C_SDATA g_time_step;
unsigned long C_SDATA g_counter1;
unsigned long C_SDATA g_speed_acumm;					   // s/w accumulator for averaging of motor speed.

unsigned long C_SDATA g_ramp_up_time;

// Declaration of bit-variables required to store motor status.
C_SBIT gb_on           C_ATBIT(g_status_word, 0);          // ON                           
C_SBIT gb_off          C_ATBIT(g_status_word, 1);          // OFF                           
C_SBIT gb_idle_state   C_ATBIT(g_status_word, 2);          // Idle_state
C_SBIT gb_hs_error     C_ATBIT(g_status_word, 3);          // Wrong hall event          
C_SBIT gb_time_out     C_ATBIT(g_status_word, 4);          // Time_out detection
C_SBIT gb_ctrap        C_ATBIT(g_status_word, 5);          // Ctrap detection
C_SBIT gb_overcurrent  C_ATBIT(g_status_word, 6);          // Overcurrent detection 

int C_SDATA g_hall_counter;
unsigned int C_SDATA g_speed_CC60;						   // variable to store the actual motor speed information.



int C_SDATA g_test_speed_kp;							   // variable to hold user specified PI proportional Gain.
int C_SDATA g_test_speed_ki;							   // variable to hold user specified PI integral Gain.
int C_SDATA g_test_speed_ymax;							   // variable to hold user specified PI saturation upper limit.
int C_SDATA g_test_speed_ymin;							   // variable to hold user specified PI saturation lower limit.

int C_SDATA g_test_current_kp;							   // variable to hold user specified PI proportional Gain.
int C_SDATA g_test_current_ki;							   // variable to hold user specified PI integral Gain.
int C_SDATA g_test_current_ymax;						   // variable to hold user specified PI saturation upper limit.
int C_SDATA g_test_current_ymin;						   // variable to hold user specified PI saturation lower limit.
extern struct pi_controller                                // PI-controller parameter            
{                                                                                
    long yn;											   // PI integral buffer.  
    int  kp;                                               // Proportional Gain          
    int  ki;											   // Integral Gain          
    int  ymax;                                             // Maximal ouput limit    
    int  ymin;                                             // Minimal ouput limit    
};
struct pi_controller C_SDATA g_pi_speed_array;
struct pi_controller C_SDATA g_pi_current_array;
//****************************************************************************
//****************************************************************************
// @Function        void TRAP_CTRL_REG_SETUP(void)     
// Description		This Function enables the TRAP feature of CCU6 module.
//----------------------------------------------------------------------------
INLINE void TRAP_CTRL_REG_SETUP(void)
{
#if DAVECG_ENABLE_TRAP
	CCU6_TRPCTR |= 0x8000;								   // Enable CTRAP.
#endif // ENABLE_TRAP == 1
}
//****************************************************************************
//****************************************************************************
// @Function        void CCU6_CC6SR_LOAD_VALUE(void)     
// Description		This Function initialises the CCU6 - shadow registers 
//					with appropraite count values.
//----------------------------------------------------------------------------
INLINE void CCU6_CC6SR_LOAD_VALUE(void)
{
#if DAVECG_BTS
CCU6_CC61SR  =  0;
CCU6_CC62SR  =  CCU6_CC61SR + T13_TIME;
#elif DAVECG_TLE
CCU6_CC61SR  =  10;
CCU6_CC62SR  =  CCU6_CC61SR + T13_TIME;
#endif      
}
//****************************************************************************
//****************************************************************************
// @Function        void ADC_DATA(void)     
// Description		This Function specifies the ADC channel to be configured
//					in injection mode.
//----------------------------------------------------------------------------
INLINE void ADC_DATA(int x)
{
#if DAVECG_CURRENT_SENSE
		ADC_DAT2 = (x);									   // Specify the ADC channel to be 'Injected'.
#endif // CURRENT_SENSE ==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 == 0)										   //execute only once when 'motor_start' command is issued.                                                                 
    {    
        
        g_once = 0x0001;                                   // Set the flag so that this code never executes until next 'motor_start' command.
        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_ref =  g_nv_start_ref;  				   // Set start speed reference into actual speed reference.           
        
        DRIVER_ENABLE();								   // Enable the driver IC if required.
        init_control();                                    // initialisation of all the variables required for motor start up.
        commutation_init();								   // initialisation of all SFRs required for motor start up.
        
    }
        
} // 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)
{

#if DAVECG_TLE
#if DAVECG_ENABLE_REFRESH_PULSE
	    PORT_ALT_SELECT();								   // Configure the port pins required for Drive refresh as output pins.
        DRIVE_REFRESH_SETUP();							   // Execute the refresh sequence for the Driver IC.
#endif // DAVECG_ENABLE_REFRESH_PULSE
#endif // DAVECG_TLE

    CCU6_MCMCTR = 0x0000;                                  // CCU6 multi channel mode control        
                                                           // Enable Shadow Tranfers direct mode
    
    CCU6_MCMOUTS = 0x8080;                                 // All Transistors OFF
  
    CCU6_TRPCTR &= 0x7FFF;                                 // Trap disable                                                                               
    
	CCU6_TCTR4 = 0x0505;                                   // CCU6 timer control register 4
                                                           // T13/T12 Reset, T13/T12 Stop -->  No PWM active 

    CC2_T78CON = 0x0000;                                   // load CAPCOM2 timer 7 and timer 8 control 
                                                           // register  -  T7 stop
    
    CC2_T7 = T7_PERIOD;                                    // load CAPCOM2 timer 7 register  50 us

    CCU6_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.														
                                    
    CCU6_TCTR4 = 0x4000;                                   // CCU6 timer control register 4 
                                                           // Shadow Tranfers by T13 Zero-Match    
        
    CCU6_IEN    &= 0x1FFF;                                 // Load CCU6 capture/compare interruptenable register IDEL and WHE disable
    
    gb_off	= 1;                                           // Status update
    gb_on	= 0;                                           // Status update

    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 = 0x0000;                                     
    }                                                                    

    if(g_direction_user > 1)
    {
        g_direction_user = 1;							   // Ensure that g_direction_user never takes an invalid value.
    }     

    g_direction = g_direction_user * 8;					   // Initialise g_direction as per the motor-direction set by user.  

} // 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 commutation_init(void)
{
//****************************************************************************
    int l_aux = 0;
    CCU6_MCMCTR = 0x0000;                                  // CCU6 multi channel mode control
                                                           // enable direct Shadow Tranfers by SW     
                                     
    CCU6_CC6SR_LOAD_VALUE();
    CCU6_T12     = CCU6_CC62SR + 1;                        // Initialize T12 timer with a sufficiently 
														   // larger value so that it doesn't generate any
														   // interrupt immediately.
                        
    CCU6_CC63SR  = PULSE_PERIOD;                           // Initialize channel3 shadow register with value corresponding
														   // to zero % duty cycle.
                                                                     
    CCU6_TCTR4   = 0x4040;                                 // select the events to trigger shadow transfers of T12 & T13.
                                     
    l_aux = (P1H & 0x0007) + g_direction;                  // Read the Hall sensor pins from the corresponding port. 

    CCU6_MCMOUTS = SP_St_Tab_r_l[l_aux] | 0x8080;		   // Load the Modulation pattern corresponding to the Hall sensor data,
														   // and force the shadow transfer of MOD pattern to the actual register.
                     
    CCU6_MCMOUTS = SP_Tab_r_l[l_aux];                      // Load the Expected Hall & Mod patterns into shadow register.
                                                     
    CCU6_IEN    |= 0x6000;                                 // enable IDLE and WHE interrupts. 
                                                           

    CCU6_TCTR4   = 0x0600;                                 // T13 Reset/Run --> Start PWM                                                       

    CCU6_MCMCTR  = 0x0014;                                 // Trigger Shadow Tranfers at correct hall
                                                           // event, synchronized to T13 Zero-Match      

    CCU6_TCTR4   = 0x0002;                                 // T12 Run
    
                                
#if DAVECG_CURRENT_SENSE
 ADC_CTR0 |= 0x0010;                                       // Disable ADC Calibration.
                                                           
#if DAVECG_BTS
 ADC_DATA(0x3000);                                         // load ADC control register 2
#elif DAVECG_TLE
 ADC_DATA(0x4000);
#endif                                                     // if BTS / elif TLE

#endif                                                     // CURRENT_SENSE == 1 

#if DAVECG_ENABLE_TRAP
    TRAP_CTRL_REG_SETUP();                                 // enable CCU6 trap
#endif
 
}                                                          //  End of function Commutation_init

//****************************************************************************
// @Function        void init_control(void)   
// Description		This function initialises the various variables required 
//					for motor start up.
//----------------------------------------------------------------------------
void init_control(void) 
{
#if DAVECG_SPEED_CALCU
    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_hall_counter   = 0x0000;
    g_speed_CC60     = 0x0000;
#endif //SPEED_CALCU == 1 
    g_counter1       = 0x00000000;
    g_time_step      = 0x00000000;
    
    g_duty_cycle = PULSE_PERIOD;                           // initialization duty cycle
    g_pic_speed_out       = 0x00000000;                    // PI-controller output (Speed control)                 
    
    g_pi_speed_array.yn   = 0x00000000;					   // Initialise PI speed integral buffer to '0'.
    g_pi_current_array.yn = 0x00000000;					   // Initialise PI current integral buffer to '0'.

#if DAVECG_CURRENT_SENSE
    g_i_counter     = 0x0000;							   // s/w time base for over-current is cleared to '0'.  
#endif //  CURRENT_SENSE == 1
     
    
} // End of function init_control


//****************************************************************************
// @Function        void speed_ref_ramp(void)
// Description		This function increments/decrements the actual speed
//					reference until it becomes equal to the speed end ref.
//----------------------------------------------------------------------------
void speed_ref_ramp(void)
{
    if(g_nv_end_ref > g_speed_ref)                         // End ref not reached?
    {                                                                         
    g_speed_ref += 1;                                      // then increment.  
    }                                                                                 
    if(g_nv_end_ref < g_speed_ref)                         // actual ref greater than end ref?
    {                                                                         
    g_speed_ref -= 1;                                      // then decrement.  
    }                                                                                 

    
} //  End of function Speed_ref_ramp
//****************************************************************************
// @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;
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 increment the reference speed by one count
          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.
#if DAVECG_KEIL
          C_CoLOAD_0_1(0, C_LSHIFT(g_nv_end_ref, 16));	   //then calculate the new 'difference in speed' the 
          C_CoSUB_0_1(0, C_LSHIFT(g_nv_start_ref0, 16));   //motor has to achieve.
          C_CoABS(); 
#endif
#if DAVECG_TASKING
          l_co_instructions = (unsigned int)g_nv_end_ref;  //then calculate the new 'difference in speed' the 
          _CoLOAD(l_co_instructions << 16);				   //motor has to achieve.
          l_co_instructions = (unsigned int)g_nv_start_ref0; 
          _CoSUB(l_co_instructions << 16);
          _CoABS();
#endif
          l_ref_difference = C_CoSTOREMAS();
          if(l_ref_difference > 1)
          { 
            l_ref_difference -= 1;       
          }
          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'
        }

}//  End of function motor_ramp_generation

//****************************************************************************
// @Function        void blink_led(void)
// Description		This function complements the LED port pin after the set
//					time has elapsed.
//----------------------------------------------------------------------------
void blink_led(void)
{
// LED Blink
    if(g_counter0 > 32000)								   // set time elapsed?
    {              
#if DAVECG_XC164CS
    P1L     ^= 0x0040;									   // then complement LED pin.
#endif
#if DAVECG_XC164CM
    P1L     ^= 0x0040;									   // then complement LED pin.
#endif
#if DAVECG_XC167CI
    P9      ^= 0x0010;									   // then complement LED pin.
#endif
    g_counter0 = 0x0000;								   // and reset the s/w time base.
    }
    g_counter0++;										   // increment s/w time base.
}
//****************************************************************************
// @Function        void duty_cycle_update(void)
// description		This function saturates the computed duty cycle between 
//					specified upper & lower limits and then loads it into
//					the CCU6 CH 3 shadow register.
//----------------------------------------------------------------------------
void duty_cycle_update(void)
{
// Duty cycle update 
#if DAVECG_KEIL
    C_CoLOAD_1_0(g_duty_cycle, 0);
    C_CoMIN_1_0(DUTY_CYCLE_MAX, 0);
    C_CoMAX_1_0(DUTY_CYCLE_MIN, 0);
    CCU6_CC63SR  = _lmac_();
    CCU6_TCTR4  = 0x4000;                                 // CCU6 timer control register 4
                                                          // Shadow Tranfers T13 enable    
#endif //KEIL == 1
#if DAVECG_TASKING
    Int_CoLimit(0,g_duty_cycle,DUTY_CYCLE_MIN,DUTY_CYCLE_MAX);
    CCU6_CC63SR = _CoSTOREMAS();
    CCU6_TCTR4  = 0x4000;                                 // CCU6 timer control register 4
                                                          // Shadow Tranfers T13 enable    
#endif //TASKING == 1

}//  End of function duty_cycle_update

//****************************************************************************
// @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.	
//----------------------------------------------------------------------------
#if DAVECG_SPEED_CALCU
int speed_calculation(unsigned int time_measurament, int* speed_counter, int limit)   
{
    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 * 8;           // Load the division factor to calculate motor speed.  
		}
    }
    g_circ_index++;                                        // Increment index for circular buffer
    if(g_circ_index > ((6 * PP) - 1))					   // 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.

}                                                          // End of function speed_calculation 
#endif

//****************************************************************************
// @Function        void adc_offset(void)
// Description		This function computes the ADC offset value, by taking 
//					65,535 samples of the ADC measured data. This computed
//					offset value is preserved in the variable g_adc_offset_res.
//----------------------------------------------------------------------------
#if DAVECG_CURRENT_SENSE
void adc_offset(void)
{
    unsigned int l_i = 0;
    unsigned int l_j = 0;
    g_adc_offset_acumm = 0;								   // clear s/w accumulator.
    for(l_i = 0; l_i < 65534; l_i++)					   // until all samples not accumulated, be in the loop.
    {
        ADC_CTR0_ADST = 1;								   // Issue 'start sampling' command to ADC.
        for(l_j = 0; l_j < 80; l_j++)					   // give some time for ADC to complete conversion.
        {
            NOP();
        }
        g_adc_offset_acumm += ((ADC_DAT & 0x0FFC) << 3);   // accumulate(integrate) the next sample.
    }
    g_adc_offset_res = g_adc_offset_acumm >> 16;		   // compute the average of all the samples.
}
#endif //(CURRENT_SENSE == 1)
//****************************************************************************
