How to use millis() instead of delay()?

How to use millis() instead of delay()? How to avoid blocking Arduino code? How to use millis() for timing? How to use millis() in multitasking?
ANSWER

The delay() function is a blocking function, it can cause some issues, such as:

Fortunately, we can use millis() instead of delay() to solve all the above issues. We will learn how to use millis() instead of a single delay() and multiple delay().

We can also apply it for multitasking.

How to use millis() instead of a single delay()

Code with delay()

#define EXE_INTERVAL 1000 void setup() { /******************* * your setup code *******************/ } void loop() { /****************** * your code block ******************/ delay(EXE_INTERVAL); }

Code with millis()

#define EXE_INTERVAL 1000 unsigned long lastExecutedMillis = 0; // vairable to save the last executed time void setup() { /******************* * your setup code *******************/ } void loop() { unsigned long currentMillis = millis(); if (currentMillis - lastExecutedMillis >= EXE_INTERVAL) { lastExecutedMillis = currentMillis; // save the last executed time /****************** * your code block ******************/ } }

To test it, you can put Serial.println("code block is executed") as your code block

How to use millis() instead of a multiple delay()

Code with delay()

#define EXE_INTERVAL_1 1000 #define EXE_INTERVAL_2 2000 void setup() { /******************* * your setup code *******************/ } void loop() { /******************** * your code block 1 ********************/ delay(EXE_INTERVAL_1); /******************** * your code block 2 ********************/ delay(EXE_INTERVAL_2); }

Code with millis()

#define EXE_INTERVAL_1 1000 #define EXE_INTERVAL_2 3000 unsigned long lastExecutedMillis_1 = 0; // vairable to save the last executed time for code block 1 unsigned long lastExecutedMillis_2 = 0; // vairable to save the last executed time for code block 2 void setup() { /******************* * your setup code *******************/ } void loop() { unsigned long currentMillis = millis(); if (currentMillis - lastExecutedMillis_1 >= EXE_INTERVAL_1) { lastExecutedMillis_1 = currentMillis; // save the last executed time /******************** * your code block 1 ********************/ } if (currentMillis - lastExecutedMillis_2 >= EXE_INTERVAL_2) { lastExecutedMillis_2 = currentMillis; // save the last executed time /******************** * your code block 1 ********************/ } }

To test it, you can use Serial.println("code block 1 is executed") and Serial.println("code block 2 is executed") as your code block 1 and your code block 2, respectively.

※ NOTE THAT:

In the above codes, each code block can be seen as a task, and multiple code blocks can be seen as multitasking.

※ OUR MESSAGES