1 #include "delay.h" 2 3 4 static u32 fac_us=0; //us延时倍乘数 5 6 void delay_init(u8 nMHz) 7 { 8 TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; 9 10 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14, ENABLE); 11 12 TIM_TimeBaseStructure.TIM_Period = 65535-1; //重载寄存器为16位寄存器,最大值65535 13 TIM_TimeBaseStructure.TIM_Prescaler = 1-1; //不分频,使用90MHz 14 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //有些定时器只支持向上计数模式 15 TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1 ; 16 TIM_TimeBaseInit(TIM14, &TIM_TimeBaseStructure); 17 18 fac_us = nMHz; 19 20 TIM_SetCounter(TIM14,0); 21 TIM_Cmd(TIM14, ENABLE); 22 23 } 24 25 26 void delay_us(u32 nus) 27 { 28 u32 ticks; 29 u32 told,tnow,tcnt=0; 30 u32 reload=65535-1; 31 ticks=nus*fac_us; 32 told=TIM14->CNT; 33 while(1) 34 { 35 tnow=TIM14->CNT; 36 if(tnow!=told) 37 { 38 if(tnow>told)tcnt+=tnow-told; //根据定时器是向上计数模式推算得来 39 else tcnt+=reload-told+tnow; //根据定时器是向上计数模式推算得来 40 told=tnow; 41 if(tcnt>=ticks)break; 42 } 43 }; 44 } 45 46 47 void delay_ms(u32 nms) 48 { 49 u32 i; 50 for(i=0;i<nms;i++) delay_us(1000); 51 }