使用Timer進行周期定時
本文引用地址:http://www.ex-cimer.com/article/201611/321633.htm在STM32的某些應用中,用戶有周期性執(zhí)行某些程序的要求,使用定時器可以產(chǎn)生固定的時間周期,滿足 這樣的需求。
STM32相關(guān)特征:
STM32高級定時器TIM1、TIM8,通用定時器TIM2、TIM3、TIM4、TIM5;
定時器最大時鐘72MHz,配合預分頻,提供靈活的時鐘周期;
每個TIM有4個獨立捕獲/比較通道,DMA/中斷功能;
通道工作在輸出比較定時模式,一個TIM至多可以提供4個不同的定時周期。
原理
TIM某輸出/捕獲通道工作在輸出比較定時模式
計數(shù)器計數(shù)至比較值時產(chǎn)生中斷,在中斷中刷新捕獲比較寄存器,這樣在相同時間間隔后可產(chǎn)生下一次中斷
TIM2時鐘設(shè)置為36MHz,預分頻設(shè)置為2,使用輸出比較-翻轉(zhuǎn)模式(Output Compare Toggle Mode)。
TIM2計數(shù)器時鐘可表達為:TIM2 counter clock = TIMxCLK / (Prescaler +1) = 12 MHz
設(shè)置TIM2_CCR1寄存器值為32768,則CC1更新頻率為TIM2計數(shù)器時鐘頻率除以CCR1寄存器值,為366.2 Hz。因此,TIM2通道1可產(chǎn)生一個頻率為183.1 Hz的周期信號。
同理,根據(jù)寄存器TIM2_CCR2 、TIM2_CCR3和 TIM2_CCR4的值,TIM2通道2可產(chǎn)生一個頻率為366.3 Hz的周期信號;TIM2通道3可產(chǎn)生一個頻率為732.4 Hz的周期信號;TIM2通道4可產(chǎn)生一個頻率為1464.8 Hz的周期信號。
可以通過示波器觀察各路輸出。
#include "stm32f10x_lib.h"
TIM_TimeBaseInitTypeDefTIM_TimeBaseStructure;
TIM_OCInitTypeDefTIM_OCInitStructure;
vu16 CCR1_Val = 32768;
vu16 CCR2_Val = 16384;
vu16 CCR3_Val = 8192;
vu16 CCR4_Val = 4096;
ErrorStatus HSEStartUpStatus;
void RCC_Configuration(void);
void GPIO_Configuration(void);
void NVIC_Configuration(void);
int main(void)
{
#ifdef DEBUG
debug();
#endif
RCC_Configuration();
NVIC_Configuration();
GPIO_Configuration();
TIM_TimeBaseStructure.TIM_Period = 65535;//這里必須是65535
TIM_TimeBaseStructure.TIM_Prescaler = 2;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;//管腳輸出模式:翻轉(zhuǎn)(TIM輸出比較觸發(fā)模式)
TIM_OCInitStructure.TIM_Channel = TIM_Channel_1;
TIM_OCInitStructure.TIM_Pulse = CCR1_Val;//翻轉(zhuǎn)周期
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;//TIM輸出比較極性低
TIM_OCInit(TIM2, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Disable);//失能TIMx在CCR1上的預裝載寄存器
TIM_OCInitStructure.TIM_Channel = TIM_Channel_2;
TIM_OCInitStructure.TIM_Pulse = CCR2_Val;
TIM_OCInit(TIM2, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Disable);
TIM_OCInitStructure.TIM_Channel = TIM_Channel_3;
TIM_OCInitStructure.TIM_Pulse = CCR3_Val;
TIM_OCInit(TIM2, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Disable);
TIM_OCInitStructure.TIM_Channel = TIM_Channel_4;
TIM_OCInitStructure.TIM_Pulse = CCR4_Val;
TIM_OCInit(TIM2, &TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Disable);
TIM_Cmd(TIM2, ENABLE);
TIM_ITConfig(TIM2, TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4, ENABLE);
while (1)
{
}
}
評論