Microcontroller Timers, Counters & PWM

A timer is a clocked state machine with selectable clock, counter width, terminal rule, capture and compare events, output actions, buffering, and interrupts. PWM is one consequence of those transitions—not a separate analog voltage source.

A hardware timer turns clock edges or external events into reproducible state transitions without requiring one CPU instruction per tick. Its behavior is determined by the source, prescaler, counting rule, width, top value, compare channels, capture path, output logic, buffering, and event flags.

Clock / eventinternal or pin Prescalertick selection Counterup / down / wrapTOP · bottom · width Input captureedge stores counter timestamp Compare + bufferingmatch at safe update boundary Output actionset · clear · toggle · PWM Flags / interrupt / triggerterminal · compare · capture Hardware timestamps and schedules edges; software owns configuration and event lifecycle.
Capture samples counter state on an external event; compare reacts when counter state reaches a programmed value; PWM combines compare actions with a periodic terminal rule.

Derive time from ticks #

For timer input frequency f_clk and prescaler N, the tick period is

[ T_{tick}=\frac{N}{f_{clk}}. ]

If a counter runs from zero through TOP inclusive, the period in a single-slope mode is

[ T_{period}=(TOP+1)T_{tick}, \qquad f_{period}=\frac{f_{clk}}{N(TOP+1)}. ]

The +1 exists because zero is a counted state. Center-aligned/dual-slope modes count up and down, so their divisor differs and must be derived from the exact terminal transitions rather than copied from the single-slope formula.

Overflow, compare, and capture #

  • Overflow/terminal event marks wraparound or reaching the configured top/bottom.
  • Output compare detects equality between counter and compare register, then can set a flag, request an interrupt, or change a pin.
  • Input capture copies the current counter into a holding register on an input edge, preserving timing even if software reads later.

Capture measures when an edge happened. Compare schedules when an output action should happen. An ISR adds latency to software work, but a hardware output-compare transition can remain tied to the timer edge.

PWM as scheduled edges #

PWM encodes a fraction of a period as high time. In a non-inverting single-slope mode, duty is approximately related to compare and top by the device's edge rules. The exact 0% and 100% endpoints can be special cases, so derive them from the waveform table.

The average of an ideal 0/V waveform is D·V, but a load does not necessarily respond to the average. Motors, LEDs, heaters, filters, switching converters, and digital inputs each respond to edge rate, current, ripple, switching loss, and bandwidth differently.

Buffered updates prevent malformed cycles #

Writing TOP or compare in the middle of a cycle can create a too-long pulse, missed match, or momentary inversion. Many timers buffer writes and transfer them at bottom, top, or another synchronization point.

That means a register read can show one value while the waveform still uses the previous active value. Correct code knows which register is buffered, when transfer occurs, and whether multiple channels update atomically.

Multi-byte and asynchronous hazards #

An 8-bit CPU may access a 16-bit timer through two byte registers and a temporary latch. Read and write order are device-defined. An interrupt that touches another 16-bit timer register between the two byte accesses can corrupt the shared temporary state on some devices.

Asynchronous timer clocks add synchronization delay. A write may remain busy until it crosses into the timer domain. Firmware must check update-busy state before the next write or sleep transition.

Frequency and pulse measurement #

For period measurement, subtract consecutive captured counts modulo the counter width. Extend the range by tracking overflows, but handle the ordering race when capture and overflow flags appear together.

For frequency counting, count external edges over a precisely measured gate interval. For duty measurement, capture alternating edges or use separate edge channels, preserving which edge produced each timestamp.

Error sources include clock tolerance, quantization of one tick, input synchronization, missed edges, counter overflow ambiguity, ISR/buffer overrun, and signal integrity. Input capture removes ISR-entry jitter from the timestamp but not those other errors.

Resource and pin ownership #

A timer may share its clock, prescaler, compare pins, capture pin, dead-time unit, interrupt vector, or synchronization register with other functions. Selecting PWM can disconnect ordinary GPIO control. A debug pin or serial route can make the desired timer output unavailable.

Inventory the whole timer instance before using one channel. The minimal model is:

clock source → prescaler → counter rule → terminal rule → compare/capture → output/event route → software acknowledgement.

Diagnostic patterns #

Symptom Likely boundary
Counter never advances clock selection, gate, sleep mode, external-edge route
Frequency off by constant factor source clock, prescaler, inclusive TOP, single/dual slope
One malformed pulse after update missing buffering or wrong update boundary
Capture values jump byte-order/latch misuse, overflow race, input noise, wrong edge
Interrupt repeats flag clear rule or terminal condition still active
Register changes but pin does not compare-output mode, pin mux, direction, conflicting owner

Start with a known clock and observable toggle, then add mode, compare, capture, and interrupts one boundary at a time.

Sources

  1. docsMCS-51 Family of Single Chip Microcomputers User's Manualpdfnotes
  2. docsATmega8A Data Sheetpdfnotes
  3. docsATmega128A Data Sheetpdfnotes
  4. docsEFM8BB51 Reference Manualpdfnotes

Searches titles, aliases, headings, summaries, and full text.↑↓ move ↵ open esc close