/*
  ******************************************************************************
  * @ app.h
  *  Time base Demo source code.
  ******************************************************************************
*/
#include "app.h"

#define TIM_CLOCK_FREQ            (10000)  

TIM_Base_InitTypeDef TIM_TimeBaseStructure;    

volatile uint32_t Timer_Update_Flag;    

void Clock_Configuration(void);
void GPIO_Configuration(void);
void NVIC_Configuration(void);   

void NVIC_Configuration(void)
{
    NVIC_ClearPendingIRQ(TIM6_IRQn);   
    NVIC_EnableIRQ(TIM6_IRQn);   
} 

void Clock_Configuration(void)
{
    System_Module_Enable(EN_TIM6);   
}  

void GPIO_Configuration(void)  
{
    // do nothing here 
}

/************************************************************************
 * function   : TIM6_Update_IRQ
 * Description: TIM6 user Interrupt Handler 
 ************************************************************************/ 
void TIM6_Update_IRQ(void)
{
	if (TIM6->SR & TIMER_SR_UIF)  
	{
		Timer_Update_Flag = 1;  
	}
	
}


void TIM6_Init(void)  
{
    uint32_t timer_clock; 
    
    timer_clock = System_Get_APBClock(); 
    
    if (System_Get_SystemClock() != System_Get_APBClock())  // if hclk/pclk != 1, then timer clk = pclk * 2  
    {
       timer_clock =  System_Get_APBClock() << 1;    
    }
    
	TIM_TimeBaseStructure.ClockDivision = TIM_CLOCKDIVISION_DIV1; 
	TIM_TimeBaseStructure.CounterMode = TIM_COUNTERMODE_UP; 
	TIM_TimeBaseStructure.RepetitionCounter = 0;  
	TIM_TimeBaseStructure.Prescaler = (timer_clock/TIM_CLOCK_FREQ) - 1;  
	TIM_TimeBaseStructure.Period = (TIM_CLOCK_FREQ/1000)*500 - 1;  // 500ms 
	    
	TIM_TimeBase_Init(TIM6, &TIM_TimeBaseStructure);           

    /* TIM IT enable */
    TIM_ITConfig(TIM6, TIM_IT_Update, ENABLE);  

    /* TIM6 enable counter */
    TIM_Cmd(TIM6, ENABLE);          
}

void Timer_Update_Test(void)
{
    /* Module Clocks Configuration */
    Clock_Configuration();

    /* NVIC Configuration */   
    NVIC_Configuration();
    
	Timer_Update_Flag = 0;   
	TIM6_Init(); 
    
	while(1)
	{
		if(Timer_Update_Flag) 
		{
			printfS("Timer Update Occurs\n"); 
			Timer_Update_Flag = 0;   
		}
	}
}


