1. Advanced-control timer(TIM1)
2.General-purpose timers(TIM2 to TIM5)
3.General-purpose timers(TIM9 to TIM11)
ps. TIM8 在STM32F411xC/E中是不能用的。
這三組有各自相對應的block diagram,根據使用不同的AHB/APB2或AHB/APB1,也會對時間計算有不同的結果,細節可自行參考RM0383 Reference manual。
STM32 Timer 每次進入中斷時間間隔計算方式:
((1+TIM_Prescaler) / 系統頻率)*(1+TIM_Period) =
((1+9599)/96Mhz) * (1+9999) = 1 sec。
main function:
int main(void)
{
RCC_ClocksTypeDef RCC_Clocks;
RCC_GetClocksFreq(&RCC_Clocks);
debug_io_init();
TIM2_Init();
/* Infinite loop */
while (1)
}
Debug GPIO(PC15) init:
void debug_io_init( void )
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOC, ENABLE );
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
GPIO_Init( GPIOC, &GPIO_InitStructure );
GPIO_ResetBits(GPIOC, GPIO_Pin_15);
GPIO_SetBits(GPIOC, GPIO_Pin_15);
}
TIM2 init:
void TIM2_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* TIM2 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
/* Enable the TIM2 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period = 10000-1;
TIM_TimeBaseStructure.TIM_Prescaler = 9600-1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ClearFlag(TIM2, TIM_FLAG_Update);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
TIM2 IRQHandler:
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
{
GPIO_ResetBits(GPIOC, GPIO_Pin_15);
GPIO_SetBits(GPIOC, GPIO_Pin_15);
GPIO_ToggleBits(GPIOC, GPIO_Pin_0);
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
驗證:
下圖為邏輯分析儀測量的結果,由圖中可看出PC15每一秒鐘會觸發一次,符合我們所預期的時間。

