Timers, Counters, Interrupts and Event HandlingIntroductionTimers and event-handling peripherals are the mechanisms that allow a microcontroller to respond to the physical world at precisely controlled times. A processor can execute instructions rapidly, but software polling alone is inefficient and may miss short-lived events. Timers measure elapsed time, counters record external events, capture units measure signal characteristics, compare units generate scheduled actions, PWM units control power and motion, watchdogs recover from software failure, and interrupt or event systems coordinate these functions with minimal processor intervention. These facilities are central to mechatronic systems. A motor controller may need a PWM waveform every 20 µs, an encoder counter may record thousands of position transitions per second, and a safety input may require a response within a few microseconds. Correct design requires more than knowing register names. The engineer must calculate clock relationships, distinguish resolution from accuracy, control latency and jitter, choose appropriate priorities, and ensure that shared data are handled safely. This chapter presents device-independent principles. Register names, timer widths, interrupt-vector arrangements, and event-routing capabilities differ among microcontroller families; therefore, the manufacturer's reference manual remains authoritative for a particular device. Learning ObjectivesAfter studying this chapter, the reader should be able to: - Explain timer, counter, capture, compare, PWM, watchdog, interrupt, and event-system operation.
- Calculate timer periods, frequencies, resolution, overflow intervals, and compare values.
- Select suitable timer modes for measurement and waveform generation.
- Analyze interrupt latency, response time, priority, and jitter.
- Design efficient interrupt-driven firmware using safe shared-data methods.
- Apply timers and event handling to a mechatronic control problem.
- Identify reliability, safety, and verification issues in real-time embedded systems.
1. Timer and Counter FoundationsA timer is a digital counter driven by a known internal clock. A counter is functionally similar but is commonly driven by transitions on an external input. In many microcontrollers, one peripheral can perform both roles. If the peripheral clock frequency is fclk and the prescaler divides that clock by N, the timer tick frequency is ftick = fclk / N where ftick and fclk are in hertz and N is dimensionless. The tick interval is Ttick = N / fclk = 1 / ftick The formulas assume a stable clock and an ideal prescaler. Clock tolerance, oscillator drift, and synchronization delays introduce practical errors. For an up-counting timer that counts from zero through a terminal value TOP, the number of timer ticks in one cycle is TOP + 1. Consequently, Tperiod = (TOP + 1) × N / fclk and fperiod = fclk / [N × (TOP + 1)] The “+1” is essential because both zero and TOP represent count states. Some timer modes use a different effective cycle length, especially center-aligned PWM, in which the counter counts up and down. The mode description must therefore be checked before applying the equation. Timer width and overflowAn unsigned timer with n bits represents values from 0 through 2n − 1. If it counts continuously upward, overflow occurs after Toverflow = 2n × N / fclk For example, a 16-bit timer clocked at 16 MHz with a prescaler of 64 has Toverflow = 216 × 64 / 16 MHz = 0.262144 s Thus, it cannot directly measure a one-second interval without overflow management or a larger effective time base. Resolution and rangeTimer resolution is the smallest interval represented by one timer tick, Ttick. A smaller prescaler improves resolution but reduces the maximum measurable interval before overflow. A larger prescaler increases range but reduces timing granularity. The selection is therefore a design trade-off. The ideal frequency error caused by integer timer division can be expressed as error = (factual − ftarget) / ftarget × 100% where factual is the frequency produced by the selected integer prescaler and terminal count. This calculation does not include oscillator tolerance. Worked Example 1: Periodic interruptA 32 MHz timer clock must generate an interrupt every 1 ms. Select a prescaler of 32. The tick frequency is ftick = 32 MHz / 32 = 1 MHz Therefore, each tick is 1 µs. The required number of ticks is 1 ms / 1 µs = 1000 ticks For an up-counter beginning at zero, set TOP = 1000 − 1 = 999 The resulting period is exactly 1 ms under the stated clock assumption. If the timer register is only 8 bits wide, this configuration is impossible in a single cycle because 999 exceeds 255; a different prescaler, timer mode, or software extension is needed. 2. Timer Operating ModesFree-running modeIn free-running mode, the timer repeatedly counts through its entire range. Software can read the count and calculate elapsed time using modular arithmetic. This mode is useful for timestamps and timeouts because it does not require an interrupt for every measurement. For an unsigned n-bit counter, elapsed ticks between two readings are commonly calculated as delta = (tnow − tstart) mod 2n This remains valid across one overflow provided that the true elapsed interval is less than one complete counter range. The limitation is important: if software checks too infrequently, multiple overflows become indistinguishable. Clear-on-compare or periodic modeThe counter resets, or is otherwise made to begin a new cycle, when it reaches a programmed terminal value. This mode directly generates periodic interrupts or output transitions. It is appropriate for sampling, task scheduling, and fixed-frequency PWM. One-shot modeA one-shot timer stops after reaching its terminal value or generates one event. It is useful for pulse generation, timeout supervision, and delayed actions. A one-shot timeout should normally be cancelled or acknowledged when the expected event arrives; otherwise an obsolete timeout may later trigger an incorrect recovery action. Up/down or center-aligned modeThe counter increases to TOP and then decreases to zero. PWM edges are symmetrically distributed around the center of the period, reducing some harmonic effects and often improving motor-drive behavior. The period includes both the upward and downward counts, so the effective count length is approximately twice TOP for common implementations. Exact endpoint behavior is device-specific. 3. Capture and Compare UnitsInput captureAn input-capture unit copies the current timer value into a capture register when a selected input edge occurs. The capture operation is hardware-timed and is more accurate than reading the timer in an interrupt routine after the edge. If two captured rising-edge values are C1 and C2, and no more than one counter wrap occurs, the interval in ticks is deltaC = (C2 − C1) mod 2n The measured period is Tsignal = deltaC × N / fclk and the signal frequency is fsignal = fclk / (N × deltaC) These formulas assume that both edges have the same polarity and that input filtering and synchronization do not introduce a changing delay. A fixed delay affects absolute timing but cancels when identical edges are compared; variable delay contributes measurement uncertainty. Input capture can measure motor speed, encoder period, pulse width, ultrasonic echo time, and frequency. To measure duty cycle, capture alternating rising and falling edges or use two capture channels. If the timer can overflow between edges, an overflow counter or a sufficiently slow prescaler is required. Output compareAn output-compare unit continuously compares the timer count with a register. On a match, it can set, clear, or toggle a pin, request an interrupt, or generate an internal event. Hardware output compare is preferable to software pin toggling because the transition occurs at a defined timer count and is less affected by instruction execution. Compare events can schedule a future action. If the current count is C and a delay of D ticks is required, software may write Ccompare = (C + D) mod 2n provided that the peripheral supports wraparound scheduling and the delay is within the unambiguous range. The compare register must be updated according to the device's buffering rules; writing too late can miss a match. 4. Pulse-Width ModulationPWM represents an average output level by varying the fraction of each period for which a digital output is active. Duty cycle is D = ton / Tperiod where ton is the active duration and Tperiod is the complete period. Expressed as a percentage, duty cycle is 100D%. For an ideal low-pass load and an active-high PWM signal, the average voltage is approximately Vavg ≈ D × VH where VH is the high-level voltage. This approximation applies to loads whose electrical or mechanical dynamics filter the switching waveform; it is not a statement that the instantaneous output is analog. For edge-aligned PWM with a timer clock and prescaler as above, TPWM = (TOP + 1) × N / fclk If the compare value is CC and the implementation produces an active pulse for CC of TOP + 1 count intervals, then D ≈ CC / (TOP + 1) The exact endpoint convention varies. Some peripherals define 0 as 0% and TOP as 100%, while others use TOP+1 as the denominator or reserve special compare values. The reference manual must be followed. PWM frequency and resolution conflict. Increasing TOP improves duty-cycle resolution but lowers frequency if the timer clock and prescaler remain fixed. A practical design also considers switching losses, electromagnetic interference, audible noise, dead time, and the safe update point for compare registers. For complementary half-bridge outputs, dead time prevents simultaneous conduction of high-side and low-side switches. Dead time reduces shoot-through risk but also distorts the effective duty cycle, particularly at small duty ratios. Hardware dead-time insertion is strongly preferred for power electronics. 5. Interrupts and Event HandlingAn interrupt is a request that causes the processor to suspend ordinary execution and transfer control to an interrupt service routine (ISR). Typical sources include timer matches, capture events, ADC completion, communication reception, fault inputs, and external pin transitions. A conventional interrupt path includes: - An event sets a peripheral flag.
- The peripheral request is enabled and routed to an interrupt line.
- The processor recognizes the request according to its masking and priority rules.
- The current context is saved, automatically or by software.
- The vector directs execution to the ISR.
- The ISR services the source, clears or acknowledges the flag, and records data or schedules work.
- Return-from-interrupt restores the interrupted context.
An ISR should be short, deterministic, and focused on urgent hardware service. Lengthy computation, formatted output, dynamic memory allocation, and blocking calls generally belong in the main loop or a real-time task. External interruptsExternal interrupts respond to a pin edge or level. Edge-triggered interrupts are appropriate for events such as encoder transitions or push-button changes, while level-sensitive interrupts can represent a sustained fault. Mechanical switches bounce, producing multiple transitions; hardware filtering, debounce circuitry, or a timed software state machine is required. An external interrupt is not automatically a safe emergency stop. A safety function may require independent hardware shutdown, redundant sensing, diagnostic coverage, and compliance with applicable machinery or functional-safety standards. The microcontroller interrupt can supplement, but should not silently replace, a properly engineered safety mechanism. Polling, interrupts, and event systemsPolling gives software direct control but consumes processor time and may have variable response latency. Interrupts reduce wasted computation and respond promptly, but introduce context-switch overhead, shared-data concerns, and priority interactions. A hardware event system can route a peripheral event directly to another peripheral without entering the CPU. For example, a timer event may trigger an ADC conversion, and the ADC result may trigger DMA. This minimizes latency and jitter. The event system is especially valuable when the required relationship is simple and deterministic. It should not be used merely for novelty: routing complexity, configuration errors, limited channels, and difficult debugging are real costs. 6. Latency, Jitter, and PriorityInterrupt latency is the elapsed time from the physical or peripheral event to the beginning of useful ISR execution. A simplified model is Tlatency = Tsync + Tcurrent + Tentry + Tpriority where Tsync is input synchronization delay, Tcurrent is the time until the processor can recognize the request, Tentry is context-save and vector-entry time, and Tpriority represents blocking by higher-priority work or disabled interrupts. The terms are implementation-dependent and may not be independently measurable. Response time includes the ISR or task work needed before the actuator or software state changes: Tresponse = Tlatency + Tservice Jitter is variation in timing from one occurrence to another. If observed response times are Ti, a useful engineering measure is peak-to-peak jitter: Jpeak-to-peak = max(Ti) − min(Ti) For a periodic control loop, jitter can alter the effective sampling instant and therefore affect phase margin and control performance. Sources include higher-priority interrupts, variable ISR paths, flash wait states, cache behavior where present, critical sections, bus contention, and asynchronous input synchronization. Priority should reflect consequence and deadline, not convenience. A hard fault shutdown generally outranks a communication packet. A high-rate timer may outrank a slow diagnostic task. However, excessive priority nesting can increase analysis complexity. Systems should define maximum interrupt-disable time and maximum blocking time, then verify them by measurement and worst-case reasoning. A useful utilization estimate for periodic interrupt-driven work is U = ∑ (Ci / Ti) where Ci is the worst-case execution time of activity i and Ti is its period or minimum inter-arrival time. This is a workload indicator, not a universal schedulability proof. Interrupt overhead, blocking, sporadic events, and deadline relationships must also be included. 7. Watchdog Timers and Fault RecoveryA watchdog timer resets the processor if software fails to refresh it within a permitted interval. Failures may result from an infinite loop, deadlock, stack corruption, clock malfunction, or unexpected peripheral state. The watchdog is not a substitute for correct software. A robust design refreshes it only after essential tasks have demonstrated progress. A separate supervisory task or health-monitoring mechanism is preferable to refreshing the watchdog unconditionally in a fast timer ISR, because the latter can conceal failure of the main application. The timeout must exceed the legitimate worst-case service interval, including startup and temporary load, but remain short enough to limit hazardous uncontrolled operation. After reset, firmware should record the reset cause, place outputs in safe states, and perform a controlled restart. Repeated watchdog resets should be detected rather than treated as normal operation. 8. Safe Interrupt-Driven Firmware DesignA disciplined design separates urgent acquisition from deferred processing. An ISR may capture a timestamp, read a hardware register, clear a flag, place data in a buffer, and signal a task. The main context may then filter data, execute control algorithms, communicate with a user interface, and log diagnostics. Shared variables require attention to atomicity and memory visibility. A variable is atomic only if the processor can read or write it indivisibly under the relevant architecture. A multi-byte counter may be torn if the ISR updates it while foreground code reads it. Common solutions include briefly disabling the relevant interrupt, using a hardware latch, reading high and low parts in a validated order, or using atomic operations supplied by the architecture. The volatile qualifier informs a compiler that a value may change outside ordinary program flow; it does not make an operation atomic, does not provide mutual exclusion, and does not establish all required memory-ordering guarantees. Ring buffers are effective for UART and sampled-data streams. A producer advances a write index, while a consumer advances a read index. The design must define full and empty conditions, index width, ownership, and what happens on overflow. Dropping the newest item, dropping the oldest item, or declaring a fault are different policies and should be selected deliberately. Interrupt flags must be cleared according to peripheral semantics. Some flags are cleared by writing one, some by reading a status register followed by a data register, and some clear automatically. Incorrect clearing can cause repeated interrupts or lost events. When several sources share a vector, the ISR should inspect all relevant flags and service them in a defined order. Recommended design sequence- State the timing deadline, event rate, and acceptable jitter.
- Select a clock source and calculate tick resolution and range.
- Choose hardware timer mode, capture/compare function, or event route.
- Determine whether a CPU interrupt is necessary or whether hardware routing/DMA is sufficient.
- Define priorities, maximum blocking time, and worst-case execution time.
- Design shared-data ownership and overflow behavior.
- Configure safe output states and fault behavior.
- Verify using a logic analyzer, oscilloscope, trace facility, and fault injection.
9. Illustrative Case: Closed-Loop DC Motor Speed ControlBackgroundConsider an illustrative 32-bit microcontroller controlling a brushed DC motor. The system uses a 20 kHz PWM drive, a quadrature encoder, and a speed-control loop executed every 1 ms. The motor must continue operating with low speed ripple while communication and diagnostics run concurrently. ProblemA polling implementation reads the encoder in the main loop. At high speed, several transitions occur between iterations, causing missed counts. PWM edges generated by software also show timing variation when serial messages are processed. The design needs accurate speed measurement, stable PWM, and bounded response time. AnalysisA 20 kHz PWM period is TPWM = 1 / 20 kHz = 50 µs Suppose a 40 MHz timer clock is available. Selecting a prescaler of 1 gives a 25 ns tick. For edge-aligned PWM, the required count length is 40 MHz / 20 kHz = 2000 ticks Thus, a typical terminal value is TOP = 1999, subject to the timer's endpoint convention. The ideal duty-cycle increment is approximately 1/2000 = 0.05 percentage points. The encoder is connected to a hardware quadrature decoder or external-counter mode. Position is accumulated in hardware, while a 1 ms timer interrupt reads the count. If the count at two loop instants is P1 and P2, the change is computed modulo the counter range. If the encoder scale is K counts per revolution and the sample interval is Ts = 1 ms, the speed in revolutions per second is speed = (P2 − P1) / (K × Ts) The sign is preserved for direction. The formula assumes that the count difference does not exceed the unambiguous counter range during one sample interval. Approach and solutionThe PWM timer generates the waveform entirely in hardware. Its compare register is updated at a safe synchronization point, preventing a partially updated pulse. The encoder peripheral counts transitions without requiring an ISR for every edge. A periodic timer event triggers the control-loop interrupt at 1 ms; where available, the event system triggers an ADC conversion at a defined PWM phase to reduce electrical-noise sensitivity. The control ISR performs only the following operations: read the encoder count, calculate or schedule the speed sample, read synchronized ADC data, execute the bounded control calculation, update the next PWM command, and set a flag for lower-priority diagnostics. Serial transmission occurs outside the control ISR through a ring buffer. A watchdog is refreshed by a health-monitoring task only after the control loop, communication service, and fault checks have reported progress. A hardware overcurrent comparator disables the power stage independently of software, while an interrupt records the fault and initiates recovery. OutcomeThe architecture eliminates missed encoder transitions, produces stable PWM timing, and makes the 1 ms control period measurable. Remaining risks include encoder noise, counter rollover, duty-update synchronization, control-loop execution time, and the effect of communication bursts on lower-priority tasks. These risks are addressed through filtering, rollover tests, scope measurements, worst-case timing analysis, and fault injection. Learning pointsThe case illustrates a general principle: use hardware for repetitive, timing-critical edges; use interrupts for bounded state updates; and defer noncritical computation. The best solution is not necessarily the one with the most interrupts. It is the one that achieves the timing and safety requirements with the smallest unnecessary software burden. 10. Limitations, Verification, and Contemporary PracticePeripheral behavior is not perfectly ideal. Oscillator tolerance produces frequency error; synchronizers add delay; input filters may reject short pulses; capture registers may overflow; and interrupt flags may be coalesced when events arrive faster than software can service them. Datasheet timing diagrams and errata are therefore part of engineering analysis. Verification should include nominal tests, boundary tests, clock variation, maximum event rates, simultaneous interrupt sources, missed-event detection, counter rollover, watchdog recovery, and power-stage fault behavior. A logic analyzer can measure pulse period and duty cycle. A scope with segmented memory can reveal rare jitter events. Cycle counters, trace modules, and GPIO timing markers can measure ISR execution time. Modern microcontrollers increasingly combine timer fabrics, configurable logic, DMA, event routers, hardware timestamping, and real-time co-processors. These capabilities can reduce CPU load and jitter but increase configuration complexity. Model-based design and automated code generation may assist development, yet generated code still requires review against the hardware reference manual and timing requirements. AI-assisted programming can suggest register configurations or test cases, but it should not be trusted to infer undocumented reset states, safety behavior, or device-specific flag-clearing rules. In safety-related products, timing analysis, diagnostic coverage, traceability, controlled configuration, and independent review may be required by the applicable domain standard. The governing principle is that a convenient interrupt solution must never compromise a demonstrable safe state. Chapter SummaryTimers convert a clock into a measurable and schedulable time base. Prescaler, terminal count, timer width, and operating mode determine period, resolution, and overflow range. Counters record external events, while input capture measures event timing without relying on software response time. Output compare schedules precise transitions, and PWM controls average power by varying duty cycle. Interrupts allow processors to respond efficiently to asynchronous events, but interrupt-driven firmware must account for latency, execution time, priority, shared data, and jitter. Hardware event systems and DMA can remove repetitive work from the CPU. Watchdogs improve fault recovery when they are refreshed only after genuine system progress. Reliable designs use hardware for timing-critical repetitive operations, keep ISRs bounded, protect shared data, define fault behavior, and verify worst-case timing experimentally and analytically. Key TermsTimer: A peripheral that counts clock ticks to measure or generate time intervals. Counter: A timer operated from external event transitions. Prescaler: A clock divider that reduces the timer input frequency. Terminal count (TOP): The programmed count value at which a timer cycle ends or an action occurs. Overflow: The transition from the maximum counter value back to zero. Input capture: Hardware storage of a timer value when an input edge occurs. Output compare: Comparison between a timer count and a programmed value to schedule an action. PWM: Pulse-width modulation, in which duty cycle controls the average effect of a switching waveform. Duty cycle: The active fraction of one PWM period. Interrupt: A request that transfers processor execution to an interrupt service routine. ISR: Interrupt service routine that responds to an interrupt source. Interrupt latency: Time from an event to the start of useful interrupt servicing. Jitter: Variation in the timing of repeated events or responses. Priority: The relative urgency assigned to competing interrupt or task sources. Event system: Hardware routing mechanism that connects peripheral events without necessarily using the CPU. Watchdog timer: A supervisory timer that resets the processor if it is not serviced on time. Atomic operation: An operation that cannot be observed in a partially completed state. Ring buffer: A circular data structure used for asynchronous producer-consumer communication. Dead time: Intentional non-overlap between complementary power-switch commands. Worst-case execution time: The maximum time required by a software activity under defined conditions. Review QuestionsShort Answer Questions- Distinguish a timer from a counter and give one application of each.
- Why does an up-counter period commonly contain TOP + 1 ticks rather than TOP ticks?
- What is the principal advantage of input capture over reading a timer inside an ISR?
- Define interrupt latency and jitter.
- Why does the
volatile qualifier not guarantee atomic access?
Long Answer Questions- Explain how prescaler selection affects timer resolution, maximum interval, and frequency error.
- Describe edge-aligned and center-aligned PWM, including their advantages and limitations in motor-drive applications.
- Explain the complete path from a peripheral event to execution of an interrupt service routine.
- Discuss how priority, blocking, ISR execution time, and shared data influence real-time behavior.
- Describe a robust watchdog strategy for a mechatronic controller and explain why unconditional watchdog refreshing is unsafe.
Analytical / Application Questions- A 48 MHz timer uses a prescaler of 16 and an up-counting terminal value of 2999. Calculate the timer period and frequency. State whether the result meets a 1 kHz requirement.
- An encoder counter changes from 65,500 to 120 on a 16-bit counter. Determine the count difference using modular arithmetic and explain the condition under which the result is valid.
- Design an event-handling architecture for a motor controller requiring 20 kHz PWM, encoder measurement, a 1 ms control loop, serial diagnostics, and independent overcurrent protection. Justify which functions should use hardware, interrupts, event routing, or deferred software tasks.
Multiple Choice Questions with AnswersQuestion 1A 32 MHz timer uses a prescaler of 32. What is the timer tick period? A. 31.25 ns B. 1 µs C. 32 µs D. 1 ms Correct Answer: B. 1 µs Question 2For an up-counting timer with TOP = 999, how many timer ticks occur in one cycle under the standard zero-through-TOP convention? A. 999 B. 1000 C. 998 D. 1024 Correct Answer: B. 1000 Question 3Which peripheral function most directly measures the timer count at an input edge? A. Output compare B. Watchdog C. Input capture D. PWM dead-time insertion Correct Answer: C. Input capture Question 4A PWM signal has a period of 50 µs and an active time of 10 µs. What is its duty cycle? A. 5% B. 20% C. 40% D. 80% Correct Answer: B. 20% Question 5Which technique generally gives the lowest CPU involvement for triggering an ADC at a precisely defined timer event? A. Polling the timer in the main loop B. A hardware event system route C. Printing a diagnostic message from an ISR D. Increasing the watchdog timeout Correct Answer: B. A hardware event system route Question 6Which quantity describes variation in the timing of otherwise repeated responses? A. Resolution B. Jitter C. Duty cycle D. Prescaler Correct Answer: B. Jitter Question 7Why is a watchdog normally refreshed only after health checks succeed? A. To increase PWM frequency B. To prevent a failed application from concealing its own failure C. To eliminate oscillator tolerance D. To convert a counter into a capture unit Correct Answer: B. To prevent a failed application from concealing its own failure Question 8A 16-bit counter changes from 65,500 to 120, with one wraparound between readings. What is the modular count difference? A. 120 B. 536 C. 65,380 D. 65,656 Correct Answer: B. 536 Question 9Which activity is generally least appropriate inside a short, timing-critical ISR? A. Capturing a timestamp B. Clearing a peripheral flag according to the manual C. Placing a sample into a buffer D. Blocking while waiting for a communication transfer Correct Answer: D. Blocking while waiting for a communication transfer Question 10What is the main purpose of dead time in complementary power-switch PWM outputs? A. To increase encoder resolution B. To prevent simultaneous conduction of opposing switches C. To remove all electromagnetic interference D. To make the watchdog independent of the clock Correct Answer: B. To prevent simultaneous conduction of opposing switches
|