微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > STM32通用定时器TIMx

STM32通用定时器TIMx

时间:11-13 来源:互联网 点击:
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;
}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top