在avr GCC的函数库中包有个非常有用的精确延时函数, #include _delay_loop_1(uint8_t __count); 参数 __count 为8bit 长度,1-256,256表示为0。 每个循环花费3个CPU周期。 所以当晶振为1Mhz时,最长延时为768us(microseconds) 比如 1 us 延时 _delay_loop_2(1); //4 cpu cycles each loop so: // 1 * 4cycle / 4Mhz = 1us _delay_loop_2(uint16_t __count); 参数 __count 为 16bit 长度,1-65536,65536被认为是0。 每个循环花费4个CPU周期。 所以当晶振为1Mhz时,最长延时为262.1 ms (milliseconds) 1*4*65536=262144 us 比如 1ms 延时 _delay_loop_2(1000); //4 cpu cycles each loop // 1000 * 4cycle / 4Mhz = 1ms _delay_us(double __us); us的精确延时,参数为double,最长为768 us。 原头文件中定义了晶振频率为1Mhz。在makefile中默认为F_CPU=8000000 #ifndef F_CPU /* prevent compiler error by supplying a default */ # warning \"F_CPU not defined for 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); } _delay_ms(double __ms); ms的精确延时,参数为double,最长为262.14 ms。 因篇幅问题不能全部显示,请点此查看更多更全内容