新聞中心

STM32通用定時器TIMx

作者: 時間:2016-11-13 來源:網(wǎng)絡(luò) 收藏
STM32計數(shù)器時鐘可由下列四種時鐘源提供:

(1)內(nèi)部時鐘(CK_INT)

本文引用地址:http://butianyuan.cn/article/201611/316145.htm

(2)外部時鐘模式1:外部輸入腳(TIx)

(3)外部時鐘模式2:外部觸發(fā)輸入(ETR)

(4)內(nèi)部觸發(fā)輸入(ITRx)

時鐘源(CK_INT)經(jīng)預(yù)分頻(PSC)后得到定時時鐘(CK_CNT),每個定時時鐘計數(shù)寄存器計數(shù)(可設(shè)向上/向下/中央對齊模式),計數(shù)寄存器計數(shù)至捕獲比較寄存器(CCR),則產(chǎn)生CC中斷;計數(shù)寄存器計數(shù)至預(yù)裝載值(ARR),則產(chǎn)生UPDATE中斷,并重裝預(yù)載值。

舉個例子:(以向上計數(shù)為例,每40us中斷一次)

  例程:
(省略RCC設(shè)置部分)


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;// 預(yù)裝初值
TIM_TimeBaseStructure.TIM_Prescaler = 36-1;// 預(yù)分頻
TIM_TimeBaseStructure.TIM_ClockDivision = 0x00; // 時鐘分頻因子(用于ETR,TIX)
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上計數(shù)
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; // 重復(fù)計數(shù)
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;
}



關(guān)鍵詞: STM32通用定時器TIM

評論


技術(shù)專區(qū)

關(guān)閉