Delay and Timing Functions
Timers and Delays
Embedded systems often need to wait before an action or repeat an action at regular intervals. You might hold an indicator on, schedule a measurement, or generate a timed output. Timers and delays determine both when an action happens and whether the processor can handle other work while waiting.
Waiting versus measuring time
A blocking delay prevents the main program from advancing to its next instruction until the wait finishes. In Arduino programs, delay(ms) requests a wait in milliseconds, while delayMicroseconds(us) requests a short wait in microseconds. Check the selected board's implementation for supported ranges and timing limits.
A blocking delay does not necessarily stop the entire microcontroller. On classic AVR Arduino boards, interrupts remain enabled during delay(), and configured hardware outputs can continue operating. However, a button check placed after the delay cannot execute until the main program reaches it.
By contrast, millis() and micros() return timestamps in milliseconds and microseconds. Reading a timestamp does not wait for a future time. You can compare timestamps repeatedly while continuing other short tasks.
Method | Main-program behavior | Suitable use |
|---|---|---|
delay() | Waits before continuing | A simple millisecond pause |
delayMicroseconds() | Waits before continuing | A short microsecond pause |
Timestamp comparison | Continues between checks | Scheduling alongside other tasks |
Configured hardware timer | Counts independently of main-program progress | Regular timing events or hardware output edges |
From clock ticks to an interval
A timer's resolution is the smallest time increment it distinguishes. Units alone do not establish resolution: a function reporting microseconds need not distinguish every individual microsecond. Resolution also differs from accuracy, which describes agreement with actual elapsed time.
For an ideal clock of frequency fclk and a prescaler that divides that frequency by P:
Here Δt is the timer tick duration, N is the number of ticks, and T is the resulting interval. Use hertz for frequency to obtain seconds.
Under the inclusive counting convention, a repeating counter cycle visits every value from 0 through compare value C, with one tick per value. Therefore:
For example, an ideal 16.0 MHz clock, P=64, and C=249 give:
Confirm the timer mode before applying this convention; other counting sequences have different formulas.
Checking elapsed time without blocking
The governing test is:
This Arduino loop fragment schedules a short action while leaving time for other tasks:
const unsigned long interval = 250UL;
unsigned long previous = 0UL;
void loop() {
unsigned long now = millis();
if (now - previous >= interval) {
previous = now;
// Perform one short scheduled action.
}
// Perform other short tasks here.
}Use >=, because successive checks may skip the exact target timestamp. Match the timestamp units to the interval units.
On classic AVR Arduino boards, these timestamps use 32-bit unsigned arithmetic. Subtraction wraps modulo 232, allowing the elapsed-time test to work across rollover when the true elapsed time since the saved timestamp remains below one full wrap. Check frequently enough to detect the interval before that ambiguity arises. A millisecond counter wraps after approximately 49.7 days.
Period, lateness, and drift
Doing work and then delaying produces a start-to-start period equal to the work time plus the delay, assuming other overhead is negligible.
With timestamp scheduling, previous = now schedules relative to the latest observed start. Repeated lateness can therefore accumulate. Using previous += interval advances the scheduled reference by a fixed interval, preserving the intended time grid when the task keeps up. It does not eliminate late execution. If several intervals are missed, choose explicitly whether to catch up or skip missed actions.
Polling adds detection latency, and varying lateness produces timing jitter. For tighter output-edge timing, consider hardware timer output facilities. A timer interrupt can schedule software, but its response also has latency.
What to remember
- Delays pause subsequent main-program work; timestamp checks allow other work between checks.
- Convert clock frequency into tick duration before counting ticks.
- Use unsigned elapsed-time subtraction and a >= comparison.
- Include execution time, polling latency, and the scheduling policy when predicting timing.
Example: Scheduling a measurement controller
A measurement controller should start one task every 100 ms. Its original program performs a task lasting exactly 12 ms, then calls delay(100). Assume an ideal clock, an exact delay, and negligible overhead beyond the stated task time.
a) Find the original start-to-start period and repetition frequency. Does it meet the 100 ms target?
Start at the beginning of one task and follow the program until the next task begins. Both the task execution and the subsequent delay lie within that complete cycle.
Take the reciprocal to obtain frequency:
The target frequency is:
The original program starts tasks every 112 ms rather than every 100 ms. Its period exceeds the target by 12 ms, so it does not meet the requested schedule under these assumptions.
b) The controller is changed to a nonblocking elapsed-time test with a 100 ms interval and the update previous += 100UL. At a reference time, previous = 1000. Subsequent checks occur at 1098, 1102, 1199, and 1201 ms. Determine which checks start tasks and calculate their lateness relative to the intended schedule. The 12 ms task runs after a successful check and finishes before the next listed check.
The saved value represents the scheduled reference, rather than necessarily the latest actual execution time. At every check, calculate now - previous, compare it with 100 ms, and advance the reference only if the task starts.
- At 1098 ms, the elapsed time is 1098−1000=98 ms. This is less than 100 ms, so no task starts and the saved reference remains ________ ms.
- At 1102 ms, the elapsed time is 1102−1000=102 ms. The task starts, and the saved reference advances to 1000+100=1100 ms.
- At 1199 ms, the elapsed time is 1199−1100=99 ms. This is less than 100 ms, so no task starts and the saved reference remains ________ ms.
- At 1201 ms, the elapsed time is 1201−1100=101 ms. The task starts, and the saved reference advances to 1100+100=1200 ms.
The intended starts are 1100 ms and 1200 ms. Their lateness values are:
Tasks start at 1102 ms and 1201 ms, respectively 2 ms and 1 ms late. Advancing the scheduled reference keeps the second target at 1200 ms despite the first late execution. It does not force the loop to check at the target instant.
c) An available 16-bit hardware timer uses an ideal 8.00 MHz clock and prescaler P=64. Its repeating cycle has one tick at every count from 0 through C, inclusive. Find the compare value for a 100 ms timing event and check that it fits. This timer is independent of the timer supporting the controller's timestamps.
First convert the prescaled clock into a tick duration:
Convert the desired period to the same unit and divide by the tick duration:
Because the cycle includes count zero, the compare value is one less than the number of ticks:
An unsigned 16-bit counter can represent values from 0 through 65535, so 12499 fits. Checking the period gives:
The compare value is 12499. This establishes the hardware event period; an action performed later by software can still experience response latency.
You are testing a microcontroller delay function configured to request 600 μs. A spare digital output and a logic analyzer are already connected and configured. Initially, the output is low and the analyzer is disarmed.
A separate calibration has established the measurement overhead, the extra time contributed to the recorded high interval by this exact pin-control sequence. Assume that overhead is repeatable and the analyzer has sufficient time resolution.
Order the actions needed to record one pulse and estimate the delay function's actual execution time. The analyzer must be armed before the output rises.
Loading ordering steps…
A controller starts a measurement task, spends exactly 18 ms completing it, and then executes a 62 ms blocking delay before starting the next measurement task. Assume the delay is exact and all other overhead is negligible. What is the start-to-start repetition frequency? Answer in Hz, to one decimal place.