运用Timer进行周期守时
在STM32的某些运用中,用户有周期性履行某些程序的要求,运用守时器能够发生固定的时刻周期,满意 这样的需求。
STM32相关特征:
STM32高档守时器TIM1、TIM8,通用守时器TIM2、TIM3、TIM4、TIM5;
守时器最大时钟72MHz,合作预分频,供给灵敏的时钟周期;
每个TIM有4个独立捕获/比较通道,DMA/中止功用;
通道作业在输出比较守时形式,一个TIM至多能够供给4个不同的守时周期。
原理
TIM某输出/捕获通道作业在输出比较守时形式
计数器计数至比较值时发生中止,在中止中改写捕获比较寄存器,这样在相同时刻距离后可发生下一次中止
TIM2时钟设置为36MHz,预分频设置为2,运用输出比较-翻转形式(Output Compare Toggle Mode)。
TIM2计数器时钟可表达为:TIM2 counter clock = TIMxCLK / (Prescaler +1) = 12 MHz
设置TIM2_CCR1寄存器值为32768,则CC1更新频率为TIM2计数器时钟频率除以CCR1寄存器值,为366.2 Hz。因而,TIM2通道1可发生一个频率为183.1 Hz的周期信号。
同理,依据寄存器TIM2_CCR2 、TIM2_CCR3和 TIM2_CCR4的值,TIM2通道2可发生一个频率为366.3 Hz的周期信号;TIM2通道3可发生一个频率为732.4 Hz的周期信号;TIM2通道4可发生一个频率为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();
NV%&&&&&%_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;//管脚输出形式:翻转(TIM输出比较触发形式)
TIM_OCInitStructure.TIM_Channel = TIM_Channel_1;
TIM_OCInitStructure.TIM_Pulse = CCR1_Val;//翻转周期
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)
{
}
}
声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/fangan/dianlu/257921.html