写了个精确延时的计时器,精度10us(因为定时器16位), 调用参数为1000000的结果是大概600ms, 差距很大啊,不知道是啥原因。
#define DELAY_TIMER TIM1
static unsigned int loop; static int wait_init = 0; void wait_us(unsigned int us) { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
unsigned short wait; unsigned short old; unsigned short now, diff; unsigned int clk;
if (wait_init == 0) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); PLL_get_clock(NULL, NULL, &clk); TIM_TimeBaseStructure.TIM_Period = 60000-1; TIM_TimeBaseStructure.TIM_Prescaler = clk/100000 - 1; //精度10us TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(DELAY_TIMER, &TIM_TimeBaseStructure); TIM_Cmd(DELAY_TIMER, ENABLE); loop = 60000; wait_init = 1; }
if (us >= 6000000) us = 5999999;
wait = (unsigned short)(us/10); old = TIM_GetCounter(DELAY_TIMER); while(1) { now = TIM_GetCounter(DELAY_TIMER); if (now >= old) diff = now - old; else diff = loop - old + now; if (diff > wait) break; } } |