Learning how to use millis instead of delay is a key principle for learning the Arduino platform. The delay() function will cause all code executing on the Arduino to come to a complete halt and it will stay halted until the delay function has completed its delay time. We often refer to the delay() function as code blocking.
The delay function can (and most likely will cause all kinds of problems in your Arduino Projects:
- Pauses, but blocks all other executing code during the time specified in parenthesis.
- You are likely to miss button presses, sensor inputs, and other events while the delay is happening.
- External outputs such as WS2812b LEDs may stop animating.
Example Code using the Delay() Function
This is a typical set of code that uses the delay() function.
/*
* HOW TO USE MILLIS INSTEAD OF DELAY
* By: TheGeekPub.com
* More Arduino Tutorials: https://www.thegeekpub.com/arduino-tutorials/
*/
#define DELAY_TIME 100 // Defines how many milliseconds we want to delay.
void setup() {
// Setup code here
}
void loop() {
// Your additional code here
delay(DELAY_TIME);
}
Using Millis instead of Delay
The millis function to the rescue! With millis you can cause a delay of sorts in your code, while still allowing background code to execute. This is perfect for projects that need multitasking!
Millis on its own does not actually cause any delays or pauses to happen. Rather millis is an Arduino function to track the number of milliseconds that have gone by since the Arduino was powered on. We can use this to our advantage to count the number of milliseconds passing in a loop.
Example Code using the Millis() Function
This is the typical code for replacing delay() with millis(). In the
/*
* HOW TO USE MILLIS INSTEAD OF DELAY
* By: TheGeekPub.com
* More Arduino Tutorials: https://www.thegeekpub.com/arduino-tutorials/
*/
#define DELAY_TIME 1000
unsigned long lastExecutedMillis = 0; // create a variable to save the last executed time
void setup() {
// Setup code here
}
void loop() {
unsigned long currentMillis = millis(); // copy the current millis to our variable
if (currentMillis - lastExecutedMillis >= DELAY_TIME) // check to see how much time has passed
{
lastExecutedMillis = currentMillis; // save the last executed time
// Your additional code here
}
}
Now that you know how to use millis instead of delay you’ll most likely want to use millis in most of your projects. It’s the far more elegant way to code and will reduce many problems with missed button presses or sensor events.
Next Steps
You can now go on to the next tutorial or go back to the index!