在WINAVR中,可以自己编写延时程序,也可以直接调用WINAVR自带的delay函数。
在调用WINAVR自带的delay函数时,有时我们想延时1秒钟时,直接写_delay_ms(1000);
可是,最后结果却不对,延时不到1秒,为什么呢?下面就来解释一下这个现象:
delay.h文件位于X:\WinAVR\avr\include\avr中。
delay.h中有两个函数--------_delay_ms(double __ms)和_delay_us(double __us),分别延时__ms*F_CPU毫秒、__us*F_CPU微秒,(单片机晶振是F_CPU MHZ)两函数的原型分别如下:
1、_delay_us(double __us)
static __inline__ void
_delay_us(double __us)
{
uint8_t __ticks;
double __tmp = ((F_CPU) / 3e6) * __us;
if (__tmp < 1.0)
__ticks = 1;
else if (__tmp > 255)
__ticks = 0; /* i.e. 256 */
else
__ticks = (uint8_t)__tmp;
_delay_loop_1(__ticks);
}
其中,该函数延时的最大时间是768/F_CPU微秒。
2、_delay_ms(double __ms)
static __inline__ void
_delay_ms(double __ms)
{
uint16_t __ticks;
double __tmp = ((F_CPU) / 4e3) * __ms;
if (__tmp < 1.0)
__ticks = 1;
else if (__tmp > 65535)
__ticks = 0; /* i.e. 65536 */
else
__ticks = (uint16_t)__tmp;
_delay_loop_2(__ticks);
}
其中,该函数延时的最大时间是262.14/F_CPU毫秒。
现在明白上面为什么不行了吧!
具体函数代码,大家可以直接到delay.h里看看。还有,以后大家在写程序时,用到编译软件自带的函数时,都可以直接到源文件里看看,以后自己也学着写一些供调用的函数或头文件,这对提高编程水平很有帮助的!
参考文献:
http://www.avrtool.com/avr/gccavr/200808/1312.html
发表评论