STM32定時(shí)器溢出模式計(jì)時(shí)設(shè)置
本文引用地址:http://m.butianyuan.cn/article/201611/318492.htm
中斷函數(shù)代碼:
主機(jī):WIN7
開(kāi)發(fā)環(huán)境:MDK4.23
MCU:STM32F103CBT6
源代碼1:
說(shuō)明:定時(shí)器采用TIM2,時(shí)鐘源為內(nèi)部8M晶振,向上溢出模式.此定時(shí)器用在延時(shí)函數(shù),最小可以延時(shí)1us,故沒(méi)有采用中斷形式定時(shí).
初始化代碼:
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);//重新將Timer設(shè)置為缺省值TIM_DeInit(TIM2);//采用內(nèi)部時(shí)鐘給TIM2提供時(shí)鐘源TIM_InternalClockConfig(TIM2);timInitStruct.TIM_ClockDivision = TIM_CKD_DIV2; //定時(shí)器基準(zhǔn)頻率8MHztimInitStruct.TIM_Prescaler = 8 - 1; //計(jì)數(shù)頻率為1us跳轉(zhuǎn)1次timInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上計(jì)數(shù)timInitStruct.TIM_RepetitionCounter = 0;timInitStruct.TIM_Period = 0; //這個(gè)值實(shí)際上就是TIMX->ARR,延時(shí)開(kāi)始時(shí)重新設(shè)定即可TIM_TimeBaseInit(TIM2, &timInitStruct);TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); //計(jì)數(shù)溢出時(shí)觸發(fā)中斷TIM_Cmd(TIM2, ENABLE); //開(kāi)啟計(jì)數(shù)器延時(shí)函數(shù)代碼:
//延時(shí)1us//最大65536usvoid _delay_us(uint16_t t){TIM_SetCounter(TIM2,0);TIM_SetAutoreload(TIM2,t - 1);//等待時(shí)間到while (TIM_GetITStatus(TIM2,TIM_FLAG_Update) == 0);//停止計(jì)數(shù)TIM_SetAutoreload(TIM2,0);//清中斷標(biāo)志TIM_ClearITPendingBit(TIM2,TIM_FLAG_Update);}//延遲1ms//最大65msvoid _delay_ms(uint8_t t){if (t > 65){t = 65;}_delay_us(t * 1000);}
源代碼2:
說(shuō)明:定時(shí)器采用TIM3,時(shí)鐘源為內(nèi)部8M晶振,向上溢出模式.此定時(shí)器用在長(zhǎng)時(shí)間計(jì)時(shí),最小計(jì)時(shí)間隔為100us,故采用中斷形式定時(shí).
初始化代碼:
//中斷NVIC設(shè)置:允許中斷,設(shè)置優(yōu)先級(jí)NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //更新事件NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //搶占優(yōu)先級(jí)0NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //響應(yīng)優(yōu)先級(jí)1NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //允許中斷NVIC_Init(&NVIC_InitStructure); //寫(xiě)入設(shè)置RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);//重新將Timer設(shè)置為缺省值TIM_DeInit(TIM3);//采用內(nèi)部時(shí)鐘給TIM3提供時(shí)鐘源TIM_InternalClockConfig(TIM3);timInitStruct.TIM_ClockDivision = TIM_CKD_DIV2; //定時(shí)器基準(zhǔn)頻率8MHztimInitStruct.TIM_Prescaler = 800 - 1; //計(jì)數(shù)頻率為100us跳轉(zhuǎn)1次timInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上計(jì)數(shù)timInitStruct.TIM_RepetitionCounter = 0;timInitStruct.TIM_Period = 0; //這個(gè)值實(shí)際上就是TIMX->ARR,延時(shí)開(kāi)始時(shí)重新設(shè)定即可TIM_TimeBaseInit(TIM3, &timInitStruct);//清溢出中斷標(biāo)志TIM_ClearFlag(TIM3, TIM_FLAG_Update);//禁止ARR預(yù)裝載緩沖器TIM_ARRPreloadConfig(TIM3, DISABLE);//開(kāi)啟中斷TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); TIM_Cmd(TIM3, ENABLE); //開(kāi)啟計(jì)數(shù)器
中斷函數(shù)代碼:
//TIM3中斷void TIM3_IRQHandler(void){if(TIM_GetITStatus(TIM3, TIM_IT_Update) == SET){TIM3->ARR = 0;//清中斷溢出標(biāo)志TIM_ClearITPendingBit(TIM3,TIM_FLAG_Update);//發(fā)送信號(hào)Sig_Table.stop_require = 1;}}
評(píng)論