您的位置 首页 传感器

STM32通用定时器TIMx

STM32计数器时钟可由下列四种时钟源提供:(1)内部时钟(CK_INT)(2)外部时钟模式1:外部输入脚(TIx)(3)外部时钟模式2:外部触发输…

STM32计数器时钟可由下列四种时钟源供给:

(1)内部时钟(CK_INT)

(2)外部时钟形式1:外部输入脚(TIx)

(3)外部时钟形式2:外部触发输入(ETR)

(4)内部触发输入(ITRx)

时钟源(CK_INT)经预分频(PSC)后得到守时时钟(CK_CNT),每个守时时钟计数寄存器计数(可设向上/向下/中心对齐形式),计数寄存器计数至捕获比较寄存器(CCR),则发生CC中止;计数寄存器计数至预装载值(ARR),则发生UPDATE中止,并重装预载值。

举个比如:(以向上计数为例,每40us中止一次)

  例程:
(省掉RCC设置部分)

void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);// for 36MHz

TIM_DeInit(TIM2);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = 1200;// 预装初值
TIM_TimeBaseStructure.TIM_Prescaler = 36-1;// 预分频
TIM_TimeBaseStructure.TIM_ClockDivision = 0x00; // 时钟分频因子(用于ETR,TIX)
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; // 重复计数
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

/*——————-*/
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 40; //40us中止一次
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Disable);

/*——————-*/
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Disable;
TIM_OCInitStructure.TIM_Pulse = 800;//PWM 800/1200
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC2Init(TIM2, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Disable);

/*——————-*/
//TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Gated);
//TIM_SelectInputTrigger(TIM2, TIM_TS_ITR0);

TIM_ARRPreloadConfig(TIM2, DISABLE);

TIM_ITConfig(TIM2, TIM_IT_CC1|TIM_IT_CC2|TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
}

/*————–中止程序——————-*/
void TIM2_IRQHandler(void)
{

uint16_t capture = 0;

if(TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)

{

if((timer_cnt1++)>49)

{

timer_cnt1 = 0;

f_2ms = 1;

}

TIM_ClearITPendingBit(TIM2, TIM_IT_CC1);

capture = TIM_GetCapture1(TIM2);

if(capture==1200)

TIM_SetCompare1(TIM2, 40);

else

TIM_SetCompare1(TIM2, capture + 40);

}

if(TIM_GetITStatus(TIM2, TIM_IT_CC2) != RESET)

{

GPIO_SetBits(P_LCDBK, LCDBK);

}

if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)

GPIO_ResetBits(P_LCDBK, LCDBK);

TIM2->SR = 0x00;
}

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/yingyong/chuanganqi/272322.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部