使用Timer進(jìn)行周期定時(shí)
本文引用地址:http://butianyuan.cn/article/201611/321633.htm在STM32的某些應(yīng)用中,用戶有周期性執(zhí)行某些程序的要求,使用定時(shí)器可以產(chǎn)生固定的時(shí)間周期,滿足 這樣的需求。
STM32相關(guān)特征:
STM32高級(jí)定時(shí)器TIM1、TIM8,通用定時(shí)器TIM2、TIM3、TIM4、TIM5;
定時(shí)器最大時(shí)鐘72MHz,配合預(yù)分頻,提供靈活的時(shí)鐘周期;
每個(gè)TIM有4個(gè)獨(dú)立捕獲/比較通道,DMA/中斷功能;
通道工作在輸出比較定時(shí)模式,一個(gè)TIM至多可以提供4個(gè)不同的定時(shí)周期。
原理
TIM某輸出/捕獲通道工作在輸出比較定時(shí)模式
計(jì)數(shù)器計(jì)數(shù)至比較值時(shí)產(chǎn)生中斷,在中斷中刷新捕獲比較寄存器,這樣在相同時(shí)間間隔后可產(chǎn)生下一次中斷
TIM2時(shí)鐘設(shè)置為36MHz,預(yù)分頻設(shè)置為2,使用輸出比較-翻轉(zhuǎn)模式(Output Compare Toggle Mode)。
TIM2計(jì)數(shù)器時(shí)鐘可表達(dá)為:TIM2 counter clock = TIMxCLK / (Prescaler +1) = 12 MHz
設(shè)置TIM2_CCR1寄存器值為32768,則CC1更新頻率為T(mén)IM2計(jì)數(shù)器時(shí)鐘頻率除以CCR1寄存器值,為366.2 Hz。因此,TIM2通道1可產(chǎn)生一個(gè)頻率為183.1 Hz的周期信號(hào)。
同理,根據(jù)寄存器TIM2_CCR2 、TIM2_CCR3和 TIM2_CCR4的值,TIM2通道2可產(chǎn)生一個(gè)頻率為366.3 Hz的周期信號(hào);TIM2通道3可產(chǎn)生一個(gè)頻率為732.4 Hz的周期信號(hào);TIM2通道4可產(chǎn)生一個(gè)頻率為1464.8 Hz的周期信號(hào)。
可以通過(guò)示波器觀察各路輸出。
#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上的預(yù)裝載寄存器
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)
{
}
}
評(píng)論