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


TIM_HandleTypeDef TIM15_Handler;  // PA2 and PA3  
volatile uint32_t Timer_Update_Flag;    

/************************************************************************
 * function   : TIM6_IRQHandler
 * Description: TIM6 Interrupt Handler 
 ************************************************************************/ 
void TIM15_IRQHandler(void)
{
	if (TIM15->SR & TIMER_SR_UIF)
	{
		Timer_Update_Flag = 1;  
	}
	
	TIM15->SR = 0;   //write 0 to clear hardware flag  
}

void TIM15_MSP_Pre_Init(TIM_HandleTypeDef * htim)
{
	HAL_TIMER_MSP_Init(&TIM15_Handler);   
}

void TIM15_MSP_Post_Init(void)
{
	GPIO_InitTypeDef gpio_init; 
	__HAL_RCC_GPIOC_CLK_ENABLE();
    
	gpio_init.Pin = GPIO_PIN_1 | GPIO_PIN_2;  //TIM15_CH1 and TIM15_CH2  
	gpio_init.Mode = GPIO_MODE_AF_PP;          
	gpio_init.Pull = GPIO_PULLUP;    
	gpio_init.Alternate = GPIO_FUNCTION_1;    
    gpio_init.Drive = GPIO_DRIVE_LEVEL3;   
	HAL_GPIO_Init(GPIOC, &gpio_init);   	 
}

void TIM15_Init(void)  
{
    uint32_t timer_clock; 
    TIM_SlaveConfigTypeDef sSlaveConfig = {0};   
    
    timer_clock = HAL_RCC_GetPCLK2Freq();  
    
    if (HAL_RCC_GetHCLKFreq() != timer_clock )  // if hclk/pclk != 1, then timer clk = pclk * 2  
    {
       timer_clock =  timer_clock << 1;    
    }
    
	TIM15_Handler.Instance = TIM15;
	TIM15_Handler.Init.ARRPreLoadEn = TIM_ARR_PRELOAD_ENABLE;    
	TIM15_Handler.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; 
	TIM15_Handler.Init.CounterMode = TIM_COUNTERMODE_UP; 
	TIM15_Handler.Init.RepetitionCounter = 0;  
	TIM15_Handler.Init.Prescaler = 0;      
	TIM15_Handler.Init.Period = 0xFFFF;   
	
	TIM15_MSP_Pre_Init(&TIM15_Handler);       
	HAL_TIMER_Base_Init(&TIM15_Handler);    
	HAL_TIM_ENABLE_IT(&TIM15_Handler, TIMER_INT_EN_UPD); 
	TIM15_MSP_Post_Init();  
    
    sSlaveConfig.SlaveMode = TIM_SLAVE_MODE_ENC1;  
	sSlaveConfig.InputTrigger = TIM_TRIGGER_SOURCE_TI1FP1;  
	sSlaveConfig.TriggerPolarity = TIM_SLAVE_CAPTURE_ACTIVE_RISING;         
	sSlaveConfig.TriggerFilter = TIM_TI1_FILTER_LVL(0);  // no filter     
	HAL_TIMER_Slave_Mode_Config(&TIM15_Handler, &sSlaveConfig);   
    
	        
}

void Timer_Update_Test(void)
{
	Timer_Update_Flag = 0;  
	TIM15_Init(); 
    printfS("Timer_Update_Test\r\n");   
    HAL_TIMER_Base_Start(TIM15_Handler.Instance);     
	while(1)
	{
		if(Timer_Update_Flag) 
		{
			printfS("Timer Update Occurs\n"); 
			Timer_Update_Flag = 0;   
		}
	}
}



