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 fclkf_{\text{clk}} and a prescaler that divides that frequency by PP:


Δt=Pfclk,T=NΔt\Delta t = \frac{P}{f_{\text{clk}}}, \qquad T = N\Delta t


Here Δt\Delta t is the timer tick duration, NN is the number of ticks, and TT is the resulting interval. Use hertz for frequency to obtain seconds.


A clock passes through a prescaler to a counter that generates a repeating timing event.


Under the inclusive counting convention, a repeating counter cycle visits every value from 00 through compare value CC, with one tick per value. Therefore:


N=C+1,T=P(C+1)fclkN=C+1, \qquad T=\frac{P(C+1)}{f_{\text{clk}}}


For example, an ideal 16.0 MHz16.0\ \text{MHz} clock, P=64P=64, and C=249C=249 give:


T=64(249+1)16.0×106 s−1=0.00100 s=1.00 msT=\frac{64(249+1)}{16.0\times10^6\ \text{s}^{-1}} =0.00100\ \text{s}=1.00\ \text{ms}


Confirm the timer mode before applying this convention; other counting sequences have different formulas.

Checking elapsed time without blocking

The governing test is:


elapsed=now−previous,act when elapsed≥interval\text{elapsed}=\text{now}-\text{previous}, \qquad \text{act when elapsed}\geq\text{interval}


This Arduino loop fragment schedules a short action while leaving time for other tasks:


C++
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 2322^{32}, 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.749.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 blocking controller cycle performs a 12 millisecond task followed by a 100 millisecond delay.


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.


T=12 ms+100 ms=112 ms=0.112 sT=12\ \text{ms}+100\ \text{ms}=112\ \text{ms}=0.112\ \text{s}


Take the reciprocal to obtain frequency:


f=1T=10.112 s=8.93 Hzf=\frac{1}{T}=\frac{1}{0.112\ \text{s}}=8.93\ \text{Hz}


The target frequency is:


ftarget=10.100 s=10.0 Hzf_{\text{target}}=\frac{1}{0.100\ \text{s}}=10.0\ \text{Hz}


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.

  1. At 1098 ms, the elapsed time is 1098−1000=98 ms1098-1000=98\ \text{ms}. This is less than 100 ms, so no task starts and the saved reference remains ________ ms.
  2. At 1102 ms, the elapsed time is 1102−1000=102 ms1102-1000=102\ \text{ms}. The task starts, and the saved reference advances to 1000+100=1100 ms1000+100=1100\ \text{ms}.
  3. At 1199 ms, the elapsed time is 1199−1100=99 ms1199-1100=99\ \text{ms}. This is less than 100 ms, so no task starts and the saved reference remains ________ ms.
  4. At 1201 ms, the elapsed time is 1201−1100=101 ms1201-1100=101\ \text{ms}. The task starts, and the saved reference advances to 1100+100=1200 ms1100+100=1200\ \text{ms}.

The intended starts are 1100 ms and 1200 ms. Their lateness values are:


L1=1102 ms−1100 ms=2 msL_1=1102\ \text{ms}-1100\ \text{ms}=2\ \text{ms}


L2=1201 ms−1200 ms=1 msL_2=1201\ \text{ms}-1200\ \text{ms}=1\ \text{ms}


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=64P=64. Its repeating cycle has one tick at every count from 0 through CC, 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:


Δt=648.00×106 s−1=8.00×10−6 s=8.00 μs\Delta t=\frac{64}{8.00\times10^6\ \text{s}^{-1}} =8.00\times10^{-6}\ \text{s}=8.00\ \mu\text{s}


Convert the desired period to the same unit and divide by the tick duration:


100 ms=100000 μs100\ \text{ms}=100000\ \mu\text{s}


N=100000 μs8.00 μs=12500N=\frac{100000\ \mu\text{s}}{8.00\ \mu\text{s}}=12500


Because the cycle includes count zero, the compare value is one less than the number of ticks:


C=N−1=12500−1=12499C=N-1=12500-1=12499


An unsigned 16-bit counter can represent values from 0 through 65535, so 12499 fits. Checking the period gives:


T=(12499+1)(8.00 μs)=100000 μs=100 msT=(12499+1)(8.00\ \mu\text{s})=100000\ \mu\text{s}=100\ \text{ms}


The compare value is 12499. This establishes the hardware event period; an action performed later by software can still experience response latency.

A classic AVR Arduino program turns on an indicator, calls delay(400), and then checks a button. The button becomes pressed 150 ms after the delay begins and stays pressed. Assume the button is checked only by the main program, with negligible instruction overhead. Which statement correctly describes the timing?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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…

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice