这delay()函数是一个非常有用的函数,几乎在所有示例中都会看到它。但是,为了提高代码效率,它并不是最好的选择,因为它会阻止 Arduino 在延迟期间执行任何操作。
为此,我们可以使用millis()功能。
millis()
这millis()函数稍微高级一些,但资源非常丰富。它允许您同时发生多个事件,而无需暂停程序。这是通过测量自程序启动以来经过的时间(以毫秒为单位)来实现的。
然后,利用间隔并连续存储最后一个事件的时间,可以制作一个简单的算法,让事件在特定时间发生,而无需暂停程序。
请参阅以下示例:
unsigned long previousMillis_1 = 0; //store time for first event
unsigned long previousMillis_2 = 0; //store time for second event
const long interval_1 = 1000; //interval for first event
const long interval_2 = 2000; //interval for second event
void setup(){
}
void loop() {
//check time since program started, and store in "currentMillis"
unsigned long currentMillis = millis();
//conditional that checks whether 1 second has passed since last event
if (currentMillis - previousMillis_1 >= interval_1) {
previousMillis_1 = millis();
//execute a piece of code, every *1 second*
}
//conditional that checks whether 2 seconds have passed since last event
if (currentMillis - previousMillis_2 >= interval_2) {
previousMillis_2 = millis();
//execute a piece of code, every *2 seconds*
}
}
虽然millis()函数是一个比delay()功能,尽早开始练习是有好处的。
网友评论