arduino的delay()函数
delay(ms) 暂停程序运行一段时间。ms 是以毫秒为单位暂停的时间(无符号长整型)。
delayMicroseconds(us) 延时函数(单位us)。功能类似delay(ms).
例:
delay(500);//暂停半秒(500毫秒)
delay()函数的工作方式非常简单。它接受单个整数(或数字)参数。此数字表示时间(以毫秒为单位)。当程序遇到这个函数时,应该等到下一行代码。然而,问题是,delay()函数并不是让程序等待的好方法,因为它被称为阻塞(blocking)函数。
/* Flashing LED * ------------ * Turns on and off a light emitting diode(LED) connected to a digital * pin, in intervals of 2 seconds. * */ int ledPin = 13; // LED connected to digital pin 13 void setup() { pinMode(ledPin, OUTPUT); // sets the digital pin as output } void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second }
arduino默认提供了两个delay函数,一个是毫秒ms级别的delay,另一个是微妙us级别的delay。
翻了翻arduino的源文件,我查到了delay实现的两个关键源函数。
一个是void _delay_loop_1(uint8_t __count),
Delay loop using an 8-bit counter \c __count, so up to 256
iterations are possible. (The value 256 would have to be passed
as 0.) The loop executes three CPU cycles per iteration, not
including the overhead the compiler needs to setup the counter
register.
Thus, at a CPU speed of 1 MHz, delays of up to 768 microseconds
can be achieved.
这是文件里对这个函数的解释,很明显,在uno的16MHz的晶振的加持下,该函数的最小延时为48us。
同理,另一个函数是void _delay_loop_2(uint16_t __count),注释我就不贴了,这是个用16位的counter实现的ms级别的delay函数,16MHz下最小延时是16ms。
同时需要注意的是,delay函数的延时是busy-waiting的延时,会一直占用着cpu的资源。
官方对这两个函数的定位是:
They are typically used to facilitate short delays in the program execution.
同时他们也给出了使用建议:
In general, for long delays, the use of hardware timers is
much preferrable, as they free the CPU, and allow for
concurrent processing of other events while the timer is
running.
当然,这是他们在编写delay这个函数时用的最小延时单元函数,但我们在日常的使用中,是根本不会用到这两个函数的,我们会使用他们的高一级封装形态,但归根到底,delay()函数其实就是对所输入的延时时长进行必要的转换从而计算出所要调用的上述两个函数的次数来进行对应的延时的操作。
但我们也要从中看到他们的局限性,那就是精度上的不足,在使用arduino进行项目设计的时候,最好就不要用long time的delay了,如果真的要做,个人建议重构delay函数或者基于项目的要求进行自己的函数适配性调整,但arduino经过几年的发展,无论是函数的可靠性还是实用性都已经非常高,所以自己重构除非有强悍的编程基础,否则是不建议做的。
- 上一篇
arduino是什么,具有哪些功能?
Arduino是一个比你的台式电脑更能够用来感应和控制现实物理世界的一套工具。 它由一个基于简易单片机并且开放源码的计算机平台,和一套为Arduino板编写程序 的开发环境组成。
- 下一篇
Arduino IDE 是什么 1.8.7官方下载
Arduino IDE是Arduino产品的软件编辑环境。简单的说就是用来写代码,下载代码的地方。任何的Arduino产品都需要下载代码后才能运作。我们所搭建的硬件电路是辅助代码来完成的,两者是缺一不可的。如同人通过大脑来控制肢体活动是一个道理。如果代码就是大脑的话,外围硬件就是肢体,肢体的活动取决于大脑,所以硬件实现取决于代码。