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?
The delay() function is a blocking function, it can cause some issues, such as:
- Prevents executing other code during the delay time
- Makes the external events be missed (e.g button press)
- Makes it difficult for other timings
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()
Arduino Code with delay()
Arduino Code with millis()
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()
Arduino Code with delay()
Arduino Code with millis()
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.
Buy Arduino
1 × Arduino UNO Buy on Amazon | |
1 × USB 2.0 cable type A/B Buy on Amazon | |
1 × Jumper Wires Buy on Amazon |