Primer
1. The common codes and PWM section
2. life often used in the following few samples,
- Alarm clock, the time given to remind
- Stopwatch (timer), statistics of time spent doing one thing
principle
Above, the timer need a clock input, at each clock trigger, do the following
1. 计数器做增加或减少的操作
2. 跟目标值做比较,达到目标则触发中断,并重新把预置值设置到计数器中
Therefore, the actual configuration steps need to be configured as follows
- The clock source and the clock frequency dividing coefficient parameter
- Preset value and the target value
- Counting, growth and reduce
- Cycle mode, single cycle or trigger
Configuration Example
feature design
Using the timer 2 control LED lamp light once every second.
Timer Configuration
-
Divider configuration, as shown, from the timer 2 AHB2 (108M) - / 2-> APB1 (54M) - * 2-> TIMER2 (108M), and therefore in order to achieve timing 1s, here dubbed 108MHz / 108100 = 10KHz, so Prescaler = 10800-1.
TIMER_BaseInitParaStructure.TIMER_Prescaler = 10800-1; /* 10KHz */
-
Configuration counting method
TIMER_BaseInitParaStructure.TIMER_CounterMode = TIMER_COUNTER_UP;
-
Configuration preset value, said first step to a 10KHz clock arranged, at a frequency of 10KHz, 10,000 counts is 1s, so TIMER_Period = 10000-1
TIMER_BaseInitParaStructure.TIMER_Period = 10000-1; /* 10000*10KHz = 1s */
- Configuration cycle mode, the default mode is the cycle count, this step can be saved, if a single-step mode, it must be configured.
TIMER_SinglePulseMode(TIMER2, TIMER_SP_MODE_REPETITIVE);
- Note that the timer interrupt, the first step must clear the timer interrupt flag, to prevent the interruption repeatedly to enter.
TIMER_ClearIntBitState(TIMER2,TIMER_INT_UPDATE);
- The complete code is as follows,
VOID TIMER2_IRQHandler(VOID)
{
if(TIMER_GetIntBitState(TIMER2,TIMER_INT_UPDATE) != RESET)
{
/* 定时器中断中,第一步必须先清除定时器中断标记,防止中断反复进入 */
TIMER_ClearIntBitState(TIMER2,TIMER_INT_UPDATE);
if (gTimerLedFlag != 0)
{
DRV_LED_On(DRV_LED1);
gTimerLedFlag = 0;
return;
}
DRV_LED_Off(DRV_LED1);
gTimerLedFlag++;
}
}
VOID DRV_TIMER_Timer2Init(VOID)
{
TIMER_BaseInitPara TIMER_BaseInitParaStructure;
NVIC_InitPara NVIC_InitStructure;
RCC_APB1PeriphClock_Enable(RCC_APB1PERIPH_TIMER2,ENABLE);
TIMER_DeInit(TIMER2);
TIMER_BaseInitParaStructure.TIMER_Prescaler = 10800-1; /* 10KHz */
TIMER_BaseInitParaStructure.TIMER_CounterMode = TIMER_COUNTER_UP;
TIMER_BaseInitParaStructure.TIMER_Period = 10000-1; /* 10000*10KHz = 1s */
TIMER_BaseInitParaStructure.TIMER_ClockDivision = TIMER_CDIV_DIV1;
TIMER_BaseInit(TIMER2,&TIMER_BaseInitParaStructure);
TIMER_INTConfig(TIMER2, TIMER_INT_UPDATE, ENABLE);
NVIC_InitStructure.NVIC_IRQ = TIMER2_IRQn;
NVIC_InitStructure.NVIC_IRQPreemptPriority = 0;
NVIC_InitStructure.NVIC_IRQSubPriority = 0;
NVIC_InitStructure.NVIC_IRQEnable = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIMER_SinglePulseMode(TIMER2, TIMER_SP_MODE_REPETITIVE);
TIMER_Enable(TIMER2,ENABLE);
}