Timer and Counter Peripherals
Timer and counter peripherals are among the most heavily used modules in any microcontroller. At their core they are free-running digital counters driven by a clock source, but the surrounding logic transforms that simple count into a versatile timing engine. A single timer block can measure the width of an incoming pulse, generate a precisely timed waveform, schedule a periodic interrupt, or count external events, often performing several of these tasks at once across independent channels that share one time base.
The value of dedicated timer hardware lies in determinism. Because the counter advances on every clock edge regardless of what the processor is doing, timing references remain stable even when the central processing unit is busy or interrupts are delayed. This independence makes timers the natural foundation for motor control, communication baud-rate generation, sensor sampling, and the housekeeping functions that keep an embedded system running on schedule.
Counter Architecture and Counting Modes
A hardware counter consists of a register that increments or decrements on each active clock edge, together with comparison and reload logic that defines its behavior at the boundaries of its range. The width of the counter, commonly sixteen or thirty-two bits, sets the maximum count before the register overflows and returns to its starting value.
Up, Down, and Center-Aligned Counting
In up-counting mode the register increases from zero to a defined maximum, then wraps back to zero and sets an overflow flag. Down-counting reverses this, decrementing from a loaded value to zero and signaling an underflow. The choice affects how compare events align in time and which edge of a generated waveform the comparison controls.
Center-aligned, or up-down, counting combines both directions: the counter ramps up to its maximum, then ramps back down to zero, repeating the triangular pattern. This mode is widely used in motor drive applications because it produces pulse-width-modulated waveforms that are symmetric about the center of each period, which reduces harmonic content and simplifies synchronized sampling.
Auto-Reload and Period Definition
The auto-reload register holds the value that defines the counting period. When the counter reaches this value, it automatically reloads and generates an update event without software intervention. Programming the auto-reload register sets the timer period directly, decoupling period control from any compare channels used for output generation.
Many timers double-buffer the auto-reload register so that a new period value takes effect only at the next update event rather than immediately. This buffering prevents glitches when the period changes during operation, ensuring that the counter always completes a clean cycle before adopting new timing parameters.
External Clock and Event Counting
When clocked from an external signal rather than the internal bus clock, a timer becomes a counter of external events. Each rising or falling edge on the input increments the register, allowing the peripheral to tally pulses from a flow meter, an optical encoder, or any other source that produces discrete transitions.
Gated and triggered modes extend this capability. In gated mode the counter advances only while an external enable signal is asserted, which measures the duration for which a condition holds true. In triggered mode an external edge starts the counter, enabling precise measurement of the interval between an external stimulus and a subsequent event.
Prescalers and Clock Selection
Few applications need the timer to count at the full system clock frequency. Prescalers and flexible clock routing adapt the raw clock to the resolution and range each task requires, trading timing granularity against the longest interval the counter can represent.
Prescaler Operation
A prescaler divides the incoming clock by a programmable factor before it reaches the counter. Dividing a 72-megahertz clock by 72, for example, yields a 1-megahertz count rate, so each count represents exactly one microsecond. The prescaler effectively extends the time a fixed-width counter can measure, at the cost of coarser resolution.
Selecting a prescaler value is a balance. A small divisor preserves fine resolution but limits the maximum interval before the counter overflows. A large divisor lengthens the achievable interval but makes each count coarser. Engineers choose the smallest prescaler that still allows the required period to fit within the counter width.
Clock Sources and Synchronization
Timers can draw their clock from the main bus clock, a separate low-frequency oscillator, an external pin, or the output of another timer. Routing one timer's update event to clock a second timer chains their ranges together, forming a wider effective counter than either provides alone.
Master-slave configurations synchronize multiple timers so that they start, stop, and reset in lockstep. A master timer broadcasts trigger signals that enable or reset its slaves, creating precisely aligned timing across several channels. Multi-phase waveform generation for three-phase motor drives depends on this coordinated operation.
Input Capture
Input capture records the value of the running counter at the instant an external event occurs. Because the hardware latches the count directly, the timestamp is immune to the variable latency that would corrupt a software reading taken inside an interrupt service routine. This precision makes input capture the standard technique for measuring the timing of incoming signals.
Edge Detection and Timestamping
A capture channel monitors an input pin for a configured transition, either rising, falling, or both. When the selected edge arrives, the channel copies the current counter value into a dedicated capture register and raises a flag. Software then reads the captured value at its leisure, knowing it reflects the exact moment of the event.
The difference between two successive captures gives the time between events. Capturing both edges of a pulse yields its width; capturing the same edge on consecutive cycles yields the period and, by extension, the frequency. Hardware capture preserves microsecond or sub-microsecond accuracy that software polling cannot match.
Pulse-Width and Frequency Measurement
Pairing two capture channels on a single input, one configured for rising edges and the other for falling edges, measures pulse width and duty cycle in a single counter cycle. Some timers automate this arrangement in a dedicated pulse-width measurement mode that resets the counter on one edge and captures it on the other.
For low-frequency signals, counting the timer ticks between edges yields accurate period measurement. For high-frequency signals, counting how many input edges occur during a fixed timer window yields frequency more accurately. Selecting the appropriate method according to the signal frequency maintains measurement precision across a wide range.
Output Compare and Waveform Generation
Output compare reverses the capture relationship: instead of recording the counter at an external event, it acts on an output when the counter reaches a programmed value. Comparing the counter against one or more compare registers generates edges, pulses, and interrupts at precisely defined moments, all referenced to the same time base.
Compare Match Actions
When the counter equals a compare register, the channel can set, clear, or toggle its output pin, generate an interrupt, or trigger a direct memory access request. Toggling on each match produces a square wave whose frequency depends on the compare value and the counter period, providing a simple programmable clock output.
Scheduling an interrupt or a peripheral trigger at a compare match allows the timer to coordinate other parts of the system. An analog-to-digital converter started by a compare event samples at an exact, jitter-free instant, which is essential when the sampling moment must align with a specific point in a control cycle.
One-Shot and Delayed Pulses
One-shot mode generates a single pulse of defined width after a defined delay, then stops. Loading the delay into one compare register and the pulse end into another produces a precisely timed output edge in response to a trigger, useful for generating strobe signals or controlled timing intervals without continuous counter operation.
Combining a delay with a captured trigger creates an event that occurs a fixed time after an external stimulus. This deterministic delay, set entirely in hardware, supports applications such as triggering a measurement a known interval after a synchronizing pulse.
Pulse-Width Modulation
Pulse-width modulation, or PWM, encodes a value as the ratio of on-time to total period in a rectangular waveform. By rapidly switching an output between high and low and varying the proportion of each state, a microcontroller controls average power delivery without dissipating energy in linear regulation. PWM is the dominant technique for motor speed control, light dimming, switching power conversion, and digital-to-analog approximation.
Generating a PWM Signal
A timer generates PWM by combining the period defined in its auto-reload register with a duty cycle defined in a compare register. The output asserts at the start of each period and deasserts when the counter reaches the compare value, so the compare value sets the on-time. Changing the compare value changes the duty cycle while the period remains fixed.
Resolution depends on the ratio of the counter clock to the PWM frequency. A higher counter clock relative to the switching frequency provides more discrete duty-cycle steps. Designers select prescaler and period values to balance switching frequency against the duty-cycle resolution the application demands.
Complementary Outputs and Dead Time
Driving a half-bridge requires two transistors that must never conduct simultaneously, because doing so would short the supply. Timers intended for motor and power control generate complementary output pairs in which one output is the logical inverse of the other, ensuring that the high-side and low-side switches operate in opposition.
Dead-time insertion adds a brief delay between turning one transistor off and the other on. This guard interval accounts for the finite turn-off time of real switching devices, preventing shoot-through current during the transition. The dead-time duration is programmable to match the characteristics of the specific power stage.
Fault Protection and Break Inputs
Power-control timers include break, or fault, inputs that force the outputs to a safe state when an external signal indicates an abnormal condition such as overcurrent or overvoltage. Because the response occurs in hardware, the outputs disable within a few clock cycles, far faster than software could intervene, protecting the power stage from damage.
After a fault, the timer can require explicit software acknowledgment before resuming output generation, ensuring that the system deliberately confirms recovery rather than restarting automatically into a possibly persistent fault condition.
Quadrature Decoding
Incremental rotary and linear encoders report position through two output channels offset by ninety degrees, a scheme known as quadrature. Many microcontroller timers include an encoder interface mode that decodes these signals directly in hardware, tracking position and direction without consuming processor cycles on every transition.
Decoding Direction and Position
The two encoder channels, conventionally labeled A and B, produce square waves whose phase relationship indicates the direction of motion. When channel A leads channel B the movement is in one direction; when B leads A the movement reverses. The timer's quadrature decoder examines the order of edges on both channels and counts up or down accordingly.
By counting transitions on both edges of both channels, the decoder achieves four times the resolution of the raw encoder cycle, a technique called four-times decoding. The accumulated count represents position, and its rate of change represents velocity, both derived entirely in hardware from the encoder waveform.
Index Pulses and Reference
Many encoders provide an index, or reference, output that pulses once per revolution. Routing this index to a timer input allows the counter to reset to a known reference at a fixed mechanical position each turn, correcting any accumulated miscounts and establishing an absolute reference within each revolution.
Noise immunity matters because mechanical and electrical disturbances can corrupt encoder edges. Input filtering rejects brief spurious transitions, and the quadrature decoder's reliance on the relative phase of two channels inherently ignores common-mode glitches that affect both lines simultaneously.
Watchdog Timers
A watchdog timer guards against software failures by demanding that the program periodically prove it is still running correctly. If the program fails to service the watchdog within a defined interval, the watchdog assumes the software has hung or gone astray and forces a system reset, restoring the device to a known state.
Operation and Servicing
The watchdog is a down-counter that the program must reset, or service, before it reaches zero. Correctly running software services the watchdog at regular points in its main loop, keeping the counter from expiring. A hang, infinite loop, or corrupted execution path stops the servicing, the counter expires, and the resulting reset recovers the system.
Placement of the servicing instruction matters. Servicing the watchdog from a low-priority task or the main loop, rather than from a high-frequency interrupt, ensures that the watchdog actually verifies the health of the application rather than merely confirming that interrupts still fire.
Windowed and Independent Watchdogs
A windowed watchdog requires servicing within a specific time window, neither too early nor too late. Servicing outside the window triggers a reset, catching faults that cause code to execute too quickly as well as those that cause it to stall. This stricter requirement provides stronger assurance that the program is executing as designed.
An independent watchdog runs from its own dedicated oscillator, separate from the main system clock. This independence keeps the watchdog operational even if a clock configuration error stops the primary oscillator, covering a class of failures that a clock-dependent watchdog would miss.
Real-Time Clocks
A real-time clock, or RTC, maintains calendar time and date through power cycles and low-power states. Unlike general-purpose timers that measure elapsed intervals, the RTC tracks wall-clock time in human terms, providing timestamps, alarms, and scheduling for the broader system.
Timekeeping and Calendar Functions
The RTC counts seconds, minutes, hours, days, months, and years, automatically handling the varying lengths of months and the insertion of leap days. A dedicated low-frequency crystal, typically oscillating at 32.768 kilohertz, drives the count, a frequency chosen because repeated binary division yields an exact one-second tick.
A backup power domain keeps the RTC running while the rest of the device is unpowered. Drawing from a small battery or supercapacitor, the RTC continues counting through main power loss, so the system recovers the correct date and time on restart without external reference.
Alarms, Wakeup, and Calibration
Alarm registers compare against the running time and generate an interrupt or wakeup event when they match. Programming an alarm allows the system to remain in a low-power state and rouse itself at a scheduled moment, a common pattern in battery-powered devices that must act periodically while conserving energy between actions.
Calibration compensates for the inevitable frequency error of the crystal. By periodically adding or removing counts, the RTC corrects systematic drift, and temperature-compensated implementations further adjust for the crystal's variation with temperature, improving long-term accuracy in applications that demand precise timekeeping.
Summary
Timer and counter peripherals convert a simple clocked register into a flexible timing engine that underpins much of embedded system behavior. Counting modes, prescalers, and clock selection define the resolution and range of the time base, while auto-reload registers set the period independently of the channels that act upon it.
Input capture and output compare connect that time base to the outside world, timestamping incoming events with hardware precision and generating outgoing edges at exact moments. Pulse-width modulation builds on output compare to control power efficiently, with complementary outputs, dead-time insertion, and fault inputs supporting demanding motor and power applications. Quadrature decoding tracks position from encoder signals without software overhead.
Watchdog timers and real-time clocks round out the family with reliability and timekeeping functions. The watchdog recovers the system from software failures, while the real-time clock maintains calendar time across power cycles and schedules wakeup events. Together these peripherals provide the deterministic timing on which dependable embedded systems are built.
Related Topics
- Peripheral Interfaces - the broader set of on-chip modules, including the PWM and DMA hardware these timers drive
- Real-Time Features - interrupt priority, hardware scheduling, and deterministic response built on timer events
- Low-Power Modes - sleep states and the RTC alarms and timer wakeup events that rouse the device on schedule
- Microcontroller Architecture - the cores, buses, and clock trees that host and drive the timer peripherals
- Microcontroller Systems - the parent overview tying together architecture, interfaces, and timing
- Timing and Synchronization - the oscillators, PLLs, and clock distribution that source timer and RTC clocks