不使用中斷實現通用定時器精確延時
阿新 • • 發佈:2018-11-25
網上大多數延時函式都是通過中斷方式的通用定時器來實現,如果實現1us的延時那麼每1us就來一次中斷,很影響cpu的效率。
本文不使用中斷通過是用通用定時器來實現精確延時。
程式碼如下(基於stm32f103)
static void udelay(uint32_t us) { uint32_t count = us; TIM_SetCounter(TIM2, count); TIM_Cmd(TIM2, ENABLE); while (count > 1)//一般改為>= 1,只是 > 1延時偶爾會不夠 { count = TIM_GetCounter(TIM2); } TIM_Cmd(TIM2, DISABLE); } static void TIM_Configuration(void)//2us { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Down; TIM_TimeBaseStructure.TIM_Period = 1; TIM_TimeBaseStructure.TIM_Prescaler = 71;//72Mhz TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); TIM_Cmd(TIM2, DISABLE); }
示波器測試抓到的5us延時如下: