millis()
Description
Returns the number of milliseconds passed since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 50 days.
Syntax
time_ms = millis()
Parameter Values
- None
Return Values
- Number of milliseconds passed since the program started. Data type: unsigned long.
Example Code
Example 1
This example code prints on the serial port the number of milliseconds passed since the Arduino board started running the code itself.
The result on Serial Monitor:
Example 2
Print a text one time per second without blocking other codes
※ NOTES AND WARNINGS:
- Please note that the return value for millis() is of type unsigned long, logic errors may occur if a programmer tries to do arithmetic with smaller data types such as int. Even signed long may encounter errors as its maximum value is half that of its unsigned counterpart.
- The return value of millis() function rolls over back to zero after roughly 50 days. If the sketch is intended to run for longer than that, It needs to make sure the rollover does not make the sketch fail. To solve it, write rollover-safe code. Let's compare the two following inequations:
- millis() >= (previousMillis + TIME_INTERVAL)
- (millis() - previousMillis) >= TIME_INTERVAL
- Mathematically, they are equivalent to each other. However, in programming, they are not. That is because the size of storage is unlimited in mathematics while it is limited to 4 bytes in Arduino programming. In programming, when the rollover happens, the first inequation makes the sketch fail while the second inequation does NOT. Therefore:
- Do NOT use if (millis() >= (previousMillis + TIME_INTERVAL)),
- Use if(millis() - previousMillis >= TIME_INTERVAL) instead
See Also
- Language : delay()
- Language : delayMicroseconds()
- Language : micros()
- Example : How to use millis() instead of delay()
- Example : Blink Without Delay
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |