micros()
Description
Returns the number of microseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 70 minutes. On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds.
Syntax
time_us = micros()
Parameter Values
- None
Return Values
- Returns the number of microseconds since the Arduino board began running the current program. Data type: unsigned long.
Example Code
The code returns the number of microseconds since the Arduino board began.
The result on Serial Monitor:
Example 2
Print a text one time per second without blocking other codes
※ NOTES AND WARNINGS:
- There are 1,000 microseconds in a millisecond and 1,000,000 microseconds in a second.
- Please note that the return value for micros() 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 micros() function rolls over back to zero after roughly 71 minutes. 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:
- micros() >= (previousMicros + TIME_INTERVAL)
- (micros() - previousMicros) >= 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 (micros() >= (previousMicros + TIME_INTERVAL)),
- Use if(micros() - previousMicros >= TIME_INTERVAL) instead
See Also
- Language : delay()
- Language : delayMicroseconds()
- Language : millis()
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |