Pause without Delay() arduino

别等时光非礼了梦想. 提交于 2019-12-02 07:46:16
user3704293

You are right, you can replace delay() with millis(). A common approach to that is to use a time comparing code pattern, that does not interrupt the main loop. This allows the Arduino to execute commands in specific frequencies or times.

The following example exemplify how you can execute a function every second second (and every fourth second) without using delay(). I think this should solves your problem and enables a pseudo-parallel execution:

// 2 sec. frequency
unsigned long interval=2000;    // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.

// 4 sec. frequency  
unsigned long interval1=4000;    // the time we need to wait
unsigned long previousMillis1=0; // millis() returns an unsigned long.

void setup() {
   //...
}

void loop() {

 // other CMD's...

 if ((unsigned long)(millis() - previousMillis) >= interval) {
    previousMillis = millis();
    // every second second
    // ... 
 }

 // other CMD's...

 if ((unsigned long)(millis() - previousMillis1) >= interval1) {
    previousMillis1 = millis();
    // every fourth second
    // ... 
 }

 // other CMD's...
}

In addition, you can already find some similar questions such Arduino Multitasking on stackoverflow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!