Diploma in Computer Architecture and Networking
Microprocessors and Microcontrollers
•
Diploma
Timers, Counters, Interrupts and DMA
Introduction
Embedded systems must measure time, count events, respond to external conditions and move data without wasting processor time. Microprocessors and microcontrollers provide dedicated hardware for these tasks through timers, counters, capture/compare units, watchdog timers, interrupt systems and direct memory access (DMA) controllers.
A timer normally advances from a regular clock source; a counter advances in response to external events. Interrupts allow hardware or software events to request immediate processor service. DMA transfers data between memory and peripherals with little or no central-processing-unit intervention. Together, these facilities enable accurate motor control, serial communication, data acquisition, pulse-width modulation (PWM), safety monitoring and real-time control.
Learning Objectives
After studying this chapter, the learner should be able to:
distinguish timers from event counters;
calculate timer periods, overflow times and reload values;
configure capture, compare and PWM functions;
explain watchdog operation and safe servicing practices;
describe interrupt priority, latency and interrupt-service routines;
configure basic DMA transfers and evaluate their advantages and limitations;
select an appropriate hardware mechanism for a control-system requirement.
1. Timer and Counter Foundations
A timer is a sequential digital circuit driven by a clock. Its register changes state at known intervals and can generate an overflow or compare event. A counter performs the same basic operation, but its input is usually an external pulse stream rather than the processor clock.
Important terms include:
Prescaler: divides the input clock before it reaches the timer.
Counter register: stores the current count.
Auto-reload register: supplies a value loaded automatically after overflow.
Overflow: transition beyond the largest representable count.
Compare match: equality between a counter and a programmed compare value.
One-shot mode: operation that stops after one timing event.
Periodic mode: automatic repetition after each interval.
For a timer clock frequency f_timer, the clock period is:
Ttick = 1 / ftimer
where T_tick is the duration of one timer tick in seconds. If the peripheral clock is f_clk and the prescaler division factor is P, then:
ftimer = fclk / P
This assumes that P is the actual division factor specified by the device. Some microcontrollers encode P−1 in a register, so the datasheet must be consulted.
For a timer that counts N ticks, the interval is:
Tinterval = N × P / fclk
The units are seconds when f_clk is expressed in hertz and P and N are dimensionless.
Overflow and Reload Calculations
For an n-bit up-counter, the number of count states is 2ⁿ. If the counter starts at zero and overflows after a complete cycle, the overflow period is:
Toverflow = 2n × P / fclk
If a reload value R is loaded into an n-bit up-counter, the number of increments before overflow is:
N = 2n − R
Therefore:
R = 2n − (Trequired × fclk / P)
The calculated tick count must be an integer in the timer’s permitted range. If it is not, the actual period is rounded and the resulting timing error should be evaluated.
Worked Example 1: Periodic Interrupt
A 16-bit timer receives a 16 MHz clock. A prescaler of 64 is selected, and the desired interrupt period is 10 ms.
The timer frequency is:
ftimer = 16 MHz / 64 = 250 kHz
Thus each tick is 4 μs. The required number of ticks is:
N = 10 ms / 4 μs = 2500
The reload value is:
R = 65536 − 2500 = 63036
In hexadecimal, R is 0xF63C. A 16-bit timer loaded with this value will overflow after 2500 ticks, assuming no synchronization delay or clock variation.
2. Timer Operating Modes
Common modes include:
Mode
Typical use
Main consideration
Up-counting
Periodic interrupts and delays
Simple configuration
Up/down counting
Symmetric PWM and motor control
Effective frequency differs from simple up-counting
One-shot
Pulse generation and timeout
Must be restarted or rearmed
Input capture
Measuring period or pulse width
Input synchronisation and overflow handling
Output compare
Precise output transitions
Compare value must be updated safely
PWM
Power and motion control
Resolution, frequency and dead time
A software delay loop is generally inferior to a hardware timer because it occupies the CPU, depends on compiler and instruction timing, and becomes inaccurate when interrupts or wait states occur. Hardware timers provide more predictable timing and permit the CPU to perform other work.
3. Capture, Compare and PWM
Input Capture
In capture mode, an input edge causes the current timer value to be copied into a capture register. Two successive captures can determine elapsed time:
∆t = (C2 − C1) × Ttick
where C₁ and C₂ are capture values. If the timer wraps around, modular arithmetic is required. For an n-bit timer, the tick difference is:
∆C = (C2 − C1) mod 2n
This is valid when fewer than one complete timer range elapses between captures. Capture is useful for measuring frequency, duty cycle, tachometer pulses and communication-bit timing.
For a periodic input with measured period T_signal, frequency is:
fsignal = 1 / Tsignal
Output Compare
In compare mode, the timer output changes state when the counter equals a programmed compare value. This produces accurately timed edges without requiring software to execute at the exact moment of transition. Compare events may set, clear or toggle a pin, trigger an ADC conversion or request an interrupt.
Pulse-Width Modulation
PWM controls the average power delivered to a load by switching between high and low states. For an ideal PWM waveform with supply voltage V_s and duty ratio D between 0 and 1:
Vaverage = D × Vs
This relationship describes the average of the switching waveform, not necessarily the voltage across an inductive motor or the output of a filtered circuit. For edge-aligned, up-counting PWM with clock frequency f_timer and period register value ARR, a common period approximation is:
fPWM = ftimer / (ARR + 1)
If the compare value is CCR, the duty ratio is approximately:
D = CCR / (ARR + 1)
Exact endpoint behaviour depends on the microcontroller’s PWM architecture. Complementary motor-drive outputs may require dead time so that high-side and low-side switches are never on simultaneously.
Timer capture and compare timing diagram
Figure: Timer capture and compare timing diagram
Figure: Input capture records timer values at successive signal edges; their difference gives elapsed time.
4. Watchdog Timers
A watchdog timer is an independent or semi-independent timer intended to recover from software failure. The application periodically performs a controlled refresh, often called “kicking” or “feeding” the watchdog. If the refresh does not occur before timeout, the watchdog resets the processor or raises a fault.
A watchdog should not be refreshed indiscriminately in a high-frequency interrupt, because a failed main program might still leave that interrupt running. A safer design has the main control task provide evidence of progress, while a supervisory routine refreshes the watchdog only when all essential tasks have completed successfully.
Good practice includes:
selecting a timeout longer than the worst legitimate execution interval;
recording reset-cause information;
using a protected configuration sequence;
designing outputs to enter a safe state after reset;
testing deadlocks, clock failure and peripheral faults;
avoiding watchdog disabling in deployed safety-related equipment.
A watchdog improves availability but is not a substitute for fault prevention, diagnostic coverage or a proper safety architecture.
5. Interrupt Systems
An interrupt is a request for processor service caused by a peripheral, external pin, timer, communication interface, software instruction or fault. The processor normally suspends the current program, saves necessary context, branches through an interrupt-vector mechanism to an interrupt-service routine (ISR), services the event and returns.
Interrupt Sequence
A typical sequence is:
A source sets a pending flag.
The interrupt controller evaluates enable and priority settings.
The CPU completes an instruction or reaches an interrupt boundary.
Hardware saves context and enters the ISR.
The ISR identifies the source, clears or acknowledges it, and performs minimal urgent work.
The ISR returns, restoring the interrupted context.
Interrupt latency is the time from the event to execution of the relevant ISR instruction. It includes synchronisation, current instruction completion, masking, higher-priority ISR execution and context-saving overhead. Response time is broader and includes the work needed to produce the required system response.
Interrupt sources may be level-sensitive or edge-sensitive. A level-sensitive request remains asserted until the peripheral is serviced; an edge-sensitive request records a transition. Incorrect flag clearing can cause repeated interrupts or lost events.
Priorities and Nested Interrupts
Priority systems allow urgent events to pre-empt less urgent ones. Nesting improves response to critical events but increases stack usage, timing complexity and the risk of priority inversion. Interrupt priorities should reflect consequences of delay, not merely the perceived importance of a peripheral.
An ISR should be short, deterministic and reentrant where necessary. It should usually capture data, clear the source and signal a foreground task. Lengthy calculations, blocking calls, dynamic memory allocation and unrestricted printing are poor ISR practices.
Shared data between an ISR and foreground code must be designed carefully. The volatile qualifier may prevent unwanted compiler optimisation, but it does not by itself make multi-byte operations atomic or provide mutual exclusion. Use atomic instructions, brief critical sections, interrupt-safe queues or hardware mechanisms as appropriate.
Interrupt Timing Example
Suppose a control interrupt occurs every 1 ms. Its worst-case execution time is 80 μs, and a communication ISR may occupy the processor for 25 μs. If both can delay the control ISR, a simple upper-bound occupancy is 105 μs, or 10.5% of the 1 ms interval, excluding context overhead. The design must also account for bursts, nesting rules and all other execution paths. Average CPU load alone is insufficient for proving real-time behaviour.
6. Direct Memory Access
DMA transfers data between a peripheral and memory, or between memory regions, using a dedicated controller. The CPU configures the source, destination, transfer length, direction, data width, increment modes and triggering event. The DMA controller then performs individual transfers or a block transfer and may interrupt the CPU on half-completion, completion or error.
Typical modes include:
Peripheral-to-memory: ADC samples or received serial data;
Memory-to-peripheral: DAC output, display data or transmitted serial data;
Memory-to-memory: buffer movement or data preparation;
Circular mode: continuous acquisition into a ring or alternating buffer;
Scatter-gather: linked descriptors for multiple non-contiguous regions.
DMA reduces CPU load and provides regular data movement. However, it does not make a system automatically deterministic. Bus arbitration can delay the CPU, and cache coherency becomes important in processors with data caches. A DMA buffer must be aligned and located in memory accessible to the DMA controller. On cached systems, software may need to clean or invalidate cache lines before or after transfer.
A common safe pattern is double buffering. DMA fills buffer A while the CPU processes buffer B; after completion, the roles exchange. The producer and consumer must agree on ownership so that the CPU never processes a buffer still being modified.
DMA Throughput Calculation
If each sample contains b bytes and the sampling rate is f_s, the minimum raw data rate is:
Rdata = b × fs
For two channels with 16-bit samples at 20 ksample/s per channel:
This is 80 kB/s before protocol, alignment or descriptor overhead. The selected bus and peripheral must sustain this rate with suitable margin.
7. Selecting the Appropriate Mechanism
A periodic timer interrupt is suitable when software must execute at a fixed rate. Output compare is preferable when a pin transition or trigger must occur at a precise timer count. Input capture is appropriate for measuring an external waveform. DMA is preferable for sustained high-rate data movement. A watchdog is required when recovery from software non-response is part of the dependability design.
These mechanisms are often combined. For example, a motor controller may use a timer to establish the PWM carrier, compare units to generate complementary outputs, ADC triggering at a defined switching phase, DMA to collect current samples and a high-priority interrupt for over-current protection.
Consider an illustrative 32-bit microcontroller in a battery-powered industrial controller. It samples battery voltage and temperature, communicates measurements over a serial link and must shut down a power stage if an over-temperature condition occurs.
Problem
Polling the ADC and serial interface causes variable sampling intervals and excessive CPU activity. A software delay also risks missing a rapid fault.
Analysis
The design requires a fixed sampling rate, efficient data movement, rapid fault response and recovery from software lock-up. A timer-triggered ADC conversion provides a stable sampling instant. DMA transfers conversion results into memory. A fault input generates a high-priority interrupt, while a watchdog supervises the main task.
Approach and Solution
A timer is configured for a 10 kHz trigger. The ADC performs voltage and temperature conversions in a fixed sequence. DMA operates in circular double-buffer mode. A half-transfer or full-transfer interrupt informs the application that a block is ready. The control task filters and evaluates the block outside the ISR. An external comparator drives an urgent fault interrupt and independently disables the power stage through hardware gating. The watchdog is refreshed only after acquisition, communication and diagnostic tasks report completion.
For a block of 100 samples per channel and two channels, each 16 bits, the buffer payload is:
100 × 2 × 2 bytes = 400 bytes
At 10 kHz, each channel contributes 10,000 samples/s, so the two-channel payload rate is 40,000 bytes/s. The DMA and memory system should be selected with margin for other traffic.
Outcome
Sampling is periodic and largely independent of CPU workload. DMA reduces per-sample interrupt overhead, while the fault path remains responsive. The watchdog provides recovery from task failure, and hardware shutdown limits the consequence of software latency.
Learning Points
The case illustrates that accurate timing, efficient transfer and safety response are separate requirements. No single peripheral solves all three. Good engineering combines timer triggering, DMA buffering, prioritised interrupts, independent protection and diagnostic supervision.
9. Design Challenges and Best Practices
Clock tolerances and oscillator drift limit absolute timing accuracy. Prescaler selection involves a trade-off between range and resolution. Timer wraparound must be handled explicitly. Synchronisation delays and digital filtering can alter measured edge times. Interrupt storms can starve foreground tasks. DMA can create memory-coherency errors and bus contention.
Recommended practice is to:
derive timing from the actual peripheral clock tree;
verify register encoding and off-by-one behaviour in the reference manual;
calculate worst-case, not average, latency and CPU load;
clear flags according to the peripheral’s documented sequence;
protect shared data and define buffer ownership;
instrument timing with a logic analyser or trace facility;
test overflow, missed events, disabled interrupts and clock faults;
document reset behaviour and safety states;
validate watchdog recovery rather than merely enabling it;
reserve hardware shutdown paths for hazards that software cannot safely manage.
In safety- or privacy-sensitive systems, event logs and diagnostic data should not expose personal information unnecessarily. Firmware changes to interrupt and DMA configuration should be reviewed, version-controlled and tested because a small register error can create uncontrolled outputs or data corruption.
Contemporary Developments
Modern microcontrollers increasingly provide event systems that connect timers, ADCs, DMA and communication peripherals without CPU intervention. Advanced DMA engines support linked descriptors, programmable triggers and secure memory regions. Real-time operating systems add interrupt-safe queues, deferred interrupt processing and deadline analysis. These features improve performance, but they also increase configuration complexity. Engineers must understand the underlying hardware rather than treating configuration tools as a substitute for verification.
Chapter Summary
Timers generate predictable time bases, whereas counters record external events. Prescalers, reload values and compare registers determine timing resolution and range. Input capture measures event intervals; output compare creates precise transitions; PWM controls average power and can trigger other peripherals. Watchdog timers improve recovery from software failure but require deliberate supervision and safe reset design. Interrupts provide responsive event handling, with latency determined by masking, priorities, current execution and hardware overhead. DMA transfers data efficiently but introduces bus arbitration, buffer ownership and cache-coherency concerns. Effective control systems combine these facilities according to timing, throughput, safety and reliability requirements.
Key Terms
Timer: Hardware that advances according to a clock.
Counter: Hardware that counts external or internal events.
Prescaler: Circuit that divides a source-clock frequency.
Overflow: Counter transition beyond its maximum state.
Auto-reload: Register that supplies a repeated timer starting value.
Input capture: Copying a timer value when an input edge occurs.
Output compare: Comparing a timer with a programmed value to trigger an action.
PWM: Periodic switching method in which duty ratio controls average power.
Duty ratio: Fraction of one PWM period for which the output is active.
Watchdog timer: Supervisory timer that resets or faults an unresponsive system.
Interrupt: Request for immediate or prioritised processor service.
ISR: Interrupt-service routine executed for an interrupt source.
Interrupt latency: Time between an event and ISR response.
Priority: Relative urgency assigned to an interrupt source.
DMA: Hardware-controlled transfer of data without per-item CPU intervention.
Circular buffer: Buffer reused continuously as data is produced and consumed.
Cache coherency: Agreement between cached data and main-memory data.
Dead time: Deliberate non-overlap between complementary switching signals.
Review Questions
Short Answer Questions
Distinguish a timer from an event counter.
What is the function of a prescaler?
Why is input capture useful for frequency measurement?
State two good practices for watchdog design.
Why should an ISR normally be short?
Long Answer Questions
Explain timer overflow and reload-value calculation, including the relevant assumptions.
Describe capture, compare and PWM modes and give one application of each.
Explain interrupt latency, priority and nesting concerns.
Describe DMA configuration, circular buffering and cache-coherency issues.
Explain how timers, interrupts, DMA and watchdogs can cooperate in a control system.
Analytical / Application Questions
A 20 MHz clock feeds a timer through a divide-by-100 prescaler. Determine the tick period and the number of ticks required for a 5 ms interval.
Design a mechanism for acquiring two ADC channels at 8 ksample/s using DMA. Specify triggering, buffer organisation and completion notification.
A motor controller occasionally produces overlapping complementary gate signals. Analyse which timer features and verification tests should be used to reduce this hazard.
Multiple Choice Questions with Answers
Question 1
A timer receives a 16 MHz clock through a divide-by-64 prescaler. What is its tick frequency?
A. 125 kHz
B. 250 kHz
C. 1 MHz
D. 16 MHz
Correct Answer: B. 250 kHz
Question 2
For a 16-bit up-counter starting at zero, how many increments occur before overflow when no reload value is used?
A. 16
B. 255
C. 65,535
D. 65,536
Correct Answer: D. 65,536
Question 3
Which timer function copies the current timer value when an external edge occurs?
A. Output compare
B. Input capture
C. Auto-reload
D. Watchdog refresh
Correct Answer: B. Input capture
Question 4
A PWM signal has a duty ratio of 0.25 and an ideal 12 V supply. What is the average of the switching waveform?
A. 3 V
B. 4 V
C. 9 V
D. 12 V
Correct Answer: A. 3 V
Question 5
What is the primary purpose of a watchdog timer?
A. To increase ADC resolution
B. To recover from software that fails to progress
C. To replace all interrupt sources
D. To store DMA descriptors permanently
Correct Answer: B. To recover from software that fails to progress
Question 6
Which action is generally appropriate in an interrupt-service routine?
A. Perform unbounded dynamic memory allocation
B. Wait indefinitely for a peripheral
C. Capture essential data and signal deferred processing
D. Print a long diagnostic report
Correct Answer: C. Capture essential data and signal deferred processing
Question 7
Which feature most directly reduces CPU intervention during continuous ADC acquisition?
A. DMA
B. Prescaler
C. Output compare only
D. Watchdog reset
Correct Answer: A. DMA
Question 8
Two successive capture values are 1,200 and 4,200, and the timer tick is 2 μs. What interval was measured, assuming no wraparound?
A. 0.6 ms
B. 3 ms
C. 6 ms
D. 8.4 ms
Correct Answer: C. 6 ms
Question 9
Why can DMA require cache maintenance on a cached processor?
A. DMA changes the CPU instruction set
B. Cache contents and main memory may not contain the same data
C. DMA disables all timer clocks
D. Cache maintenance increases ADC voltage
Correct Answer: B. Cache contents and main memory may not contain the same data
Question 10
What is the purpose of dead time in complementary power-switching outputs?
A. To ensure both switches are always on
B. To prevent simultaneous conduction during transitions
C. To double the timer clock
D. To eliminate the need for a watchdog
Correct Answer: B. To prevent simultaneous conduction during transitions
Microprocessors and Microcontrollers
Chapter 9
of 14