/***********************************************************************
 * Filename    : app.c
 * Description : app source file
 * Author(s)   : xwl  
 * version     : V1.0
 * Modify date : 2020-04-07  
 ***********************************************************************/
#include  "app.h"


#define PWM_OUTPUT_CHANNEL1    TIM_CHANNEL_1   

#define TIM_CLOCK_FREQ            (8000000U)  

TIM_HandleTypeDef TIM1_Handler;     

extern void TIM1_MSP_Pre_Init(TIM_HandleTypeDef * htim); 
extern void TIM1_MSP_Post_Init(void);      
/*********************************************************************************
* Function    : TIM1_Init      
* Description : timer 1 initiation, includes clock, io, configuration 
* Input       : none    
* Output      : none 
* Author      : xwl                       
**********************************************************************************/  
void TIM1_Init(void)  
{  
	TIM_OC_InitTypeDef Tim_OC_Init_Para;   
    uint32_t timer_clock;
    
    timer_clock = HAL_RCC_GetPCLK2Freq();  // TIM1 is on APB2  
    
    if (HAL_RCC_GetHCLKFreq() != timer_clock)  // if hclk/pclk != 1, then timer clk = pclk * 2  
    {
       timer_clock =  timer_clock << 1;     
    }
	
	TIM1_Handler.Instance = TIM1;
	TIM1_Handler.Init.ARRPreLoadEn = TIM_ARR_PRELOAD_ENABLE;        
	TIM1_Handler.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; 
	TIM1_Handler.Init.CounterMode = TIM_COUNTERMODE_UP; 
	TIM1_Handler.Init.RepetitionCounter = 0;  
	TIM1_Handler.Init.Prescaler = (timer_clock/TIM_CLOCK_FREQ) - 1; 
	if (timer_clock%TIM_CLOCK_FREQ > TIM_CLOCK_FREQ/2) 
	{
		TIM1_Handler.Init.Prescaler = TIM1_Handler.Init.Prescaler + 1;  
	}
	TIM1_Handler.Init.Period = (TIM_CLOCK_FREQ/1000000)*10 - 1;  // period = 10us      
	
	TIM1_MSP_Pre_Init(&TIM1_Handler);       
	HAL_TIMER_Base_Init(&TIM1_Handler);  
	
	Tim_OC_Init_Para.OCMode = OUTPUT_MODE_PWM1;  
	Tim_OC_Init_Para.OCIdleState = OUTPUT_IDLE_STATE_0;
	Tim_OC_Init_Para.OCNIdleState = OUTPUT_IDLE_STATE_0;      
	Tim_OC_Init_Para.OCPolarity = OUTPUT_POL_ACTIVE_HIGH;  
	Tim_OC_Init_Para.OCNPolarity = OUTPUT_POL_ACTIVE_HIGH;    
	Tim_OC_Init_Para.OCFastMode =  OUTPUT_FAST_MODE_DISABLE;  
	Tim_OC_Init_Para.Pulse = (TIM1_Handler.Init.Period + 1)/2;   // 50% duty cycle   	
	HAL_TIMER_Output_Config(TIM1_Handler.Instance, &Tim_OC_Init_Para, PWM_OUTPUT_CHANNEL1);    
    
	TIM1_MSP_Post_Init();   
	          
}

/*********************************************************************************
* Function    : Timer_PWM_Output_Test      
* Description : test function ,output period=10us 50% duty PWM waveform  
* Input       : none    
* Output      : none 
* Author      : xwl                       
**********************************************************************************/  
void Timer_PWM_Output_Test(void)  
{
	TIM1_Init(); 
    HAL_TIM_ENABLE_IT(&TIM1_Handler, TIM_IT_CC1); 
    
	HAL_TIM_PWM_Output_Start(TIM1_Handler.Instance, PWM_OUTPUT_CHANNEL1);       
    
	while(1)
	{

	}
}

