Having precise timing in microcontrollers is important in many projects. For
this you can use the two libraries presented in this article - millis &
micros.
millis library triggers a timer interrupt every 1 millisecond and
increments the milliseconds variable. The user can select the size of the
milliseconds variable ranging from char (8 bits) to long long (64 bits) with
an overflow from 255 milliseconds to 584.9 million years.
micros library is almost the same as millis but for
microseconds. The overflow is between 255 microseconds and 584942 years.
For both libraries the user can select which timer to use: Timer0, Timer1,
Timer2, Timer3 or Timer4.
In the case of millis library, it is recommended that other interrupts
take less than 1 millisecond to complete otherwise the millis timer
interrupt will be delayed. For the micros the ISRs must finish in less
than 100 microseconds. The faster the CPU clock the better.
For the milliseconds and microseconds variable decide if you really need a 32
or 64 variable (long and long long) because the bigger the variable the longer
it takes to increment it. For example on a 1MHz CPU it takes about 77
microseconds to increment a long long variable.