STM32如何設(shè)置定時(shí)器
下面以stm32的TIM2作為實(shí)例一步步配置成為定時(shí)器:
第一種
對(duì)定時(shí)器的基本配置
TIM_TimeBaseStructure.TIM_Period = 1000; //設(shè)置自動(dòng)裝載寄存器
TIM_TimeBaseStructure.TIM_Prescaler = 35999; //分頻計(jì)數(shù)
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //選擇向上計(jì)數(shù)
TIM_TimeBaseInit(TIM2, TIM_TimeBaseStructure);
TIM_Cmd(TIM2, ENABLE); //是能定時(shí)器
始能定時(shí)器的中斷:
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
在開(kāi)啟時(shí)鐘里一定要打開(kāi)TIM2的時(shí)鐘,函數(shù)表達(dá)式如下:
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
4:中斷向量函數(shù)的編寫(xiě):
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
#ifdef VECT_TAB_RAM //如果程序在ram中調(diào)試那么定義中斷向量表在Ram中否則在Flash中
/* Set the Vector Table base location at 0x20000000 */
NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0);
#else /* VECT_TAB_FLASH */
/* Set the Vector Table base location at 0x08000000 */
NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0);
#endif
/* Enable the TIM2 global Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQChannel;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(NVIC_InitStructure);
}
5:中斷函數(shù)的編寫(xiě):
當(dāng)有TIM2的無(wú)論哪個(gè)中斷觸發(fā)中斷發(fā)生那么就會(huì)進(jìn)入這個(gè)函數(shù)
TIM2_IRQHandler(void)
所以這個(gè)更新事件的中斷判斷要依靠以下語(yǔ)句:
if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
按照以上步驟配置可以順利進(jìn)行定時(shí)器的基本定時(shí)應(yīng)用
第二種方法:
/* Enable TIM2 Update interrupt [TIM2溢出中斷允許]*/
TIM_ITConfig(TIM2, TIM_IT_CC1, ENABLE);
中斷中的設(shè)置為:
if (TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)
評(píng)論