#include "hdl_pwm.h"

/*unit 0.01us*/
static void TmrAConfig(uint32_t t)
{
	
		stc_clock_freq_t sysFrq;
	
	  CLK_GetClockFreq(&sysFrq);
	
	  uint32_t peroid = 1.0 *sysFrq.u32Pclk1Freq / t;
	
    stc_tmra_init_t stcTmraInit;
    stc_tmra_pwm_init_t stcPwmInit;

    /* 1. Enable TimerA peripheral clock. */
    FCG_Fcg2PeriphClockCmd(TMRA_PERIPH_CLK, ENABLE);

    /* 2. Set a default initialization value for stcTmraInit. */
    (void)TMRA_StructInit(&stcTmraInit);

    /* 3. Modifies the initialization values depends on the application. */
    stcTmraInit.sw_count.u8CountMode = TMRA_MD;
    stcTmraInit.sw_count.u8CountDir  = TMRA_DIR;
    stcTmraInit.u32PeriodValue = (peroid-1);
    (void)TMRA_Init(TMRA_UNIT, &stcTmraInit);

    /* 4. Set the comparison reference value. */
#if (APP_FUNC == APP_FUNC_NORMAL_SINGLE_PWM)
    (void)TMRA_PWM_StructInit(&stcPwmInit);
		
    stcPwmInit.u32CompareValue = 0;
		stcPwmInit.u16PeriodMatchPolarity =  TMRA_PWM_HIGH;		
    GPIO_SetFunc(TMRA_PWM_PORT, TMRA_PWM_PIN, TMRA_PWM_PIN_FUNC);
    (void)TMRA_PWM_Init(TMRA_UNIT, TMRA_PWM_CH, &stcPwmInit);
    TMRA_PWM_OutputCmd(TMRA_UNIT, TMRA_PWM_CH, ENABLE);
#endif

}


void hdl_pwm_init(int frq){

	   /* MCU Peripheral registers write unprotected. */
    LL_PERIPH_WE(LL_PERIPH_GPIO | LL_PERIPH_FCG | LL_PERIPH_PWC_CLK_RMU);
	
    /* Configures TimerA. */
    TmrAConfig( frq);
	
    /* MCU Peripheral registers write protected. */
    LL_PERIPH_WP(LL_PERIPH_GPIO | LL_PERIPH_FCG | LL_PERIPH_PWC_CLK_RMU);

}

void hdl_pwm_enable(void){

    /* Starts TimerA. */
    TMRA_Start(TMRA_UNIT);
}

void hdl_pwm_disable(void){

    /* Starts TimerA. */
    TMRA_Stop(TMRA_UNIT);
}

void hdl_pwm_set_duty(int duty){

	  uint32_t period = TMRA_GetPeriodValue(TMRA_UNIT)+1;
	
	  uint32_t val = duty*0.01*period;
	
	  if(val <1){
		   val =1;
		}
		
		if(val >period){
			 val =period;
		}
		
		TMRA_Stop(TMRA_UNIT);
	  TMRA_SetCountValue(TMRA_UNIT,0);
    TMRA_SetCompareValue(TMRA_UNIT,TMRA_PWM_CH,val-1);
		TMRA_Start(TMRA_UNIT);
}




