Skip to content
BetterDL

Timer

Also called: hardware timer, timer peripheral, timer/counter

A counter used to measure time: it counts clock cycles and raises a flag or event when it reaches a set value, then usually starts over.

A timer is a counter whose input is a clock of known frequency. Counting cycles is the same as measuring time: at 1 MHz, each count is 1 µs.

A typical microcontroller timer is a synchronous mod n counter:

  • it counts up on every tick (sometimes after a divider called a prescaler slows the clock first);
  • when it reaches the value in a period or compare register it raises a flag or interrupt and goes back to 0.

Because the clear is synchronous, the counter must sit in N − 1 for the last full period, so many timers ask you to write N − 1 into the period register to get N ticks per cycle. That's the same off-by-one as any synchronous-clear mod-N counter.

Timers blink LEDs, generate PWM for motors, time out serial links and schedule tasks. A down counter works just as well: load the count, count to 0, raise a flag.

Worked examples

Example

A 1 ms tick from a 1 MHz clock

A timer is clocked at 1 MHz. You want an event every 1 ms.

  1. 1.

    1 ms ÷ 1 µs = 1000 ticks, so the counter must have modulus 1000.

  2. 2.

    Flip-flops: 2⁹ = 512 is too few, 2¹⁰ = 1024 is enough → 10 bits.

  3. 3.

    With a synchronous clear, detect the last good state: write 999 into the period register.

  4. 4.

    The counter runs 0 to 999 and fires once every 1000 µs = 1 ms.

Example

A watch crystal

A watch crystal runs at 32 768 Hz. How do you get a 1 Hz seconds tick?

  1. 1.

    32 768 = 2¹⁵, a power of 2.

  2. 2.

    So a plain 15-bit binary counter does it: the top bit, Q14, runs at 32 768 / 2¹⁵ = 1 Hz.

  3. 3.

    Cascade a mod-60 counter after it to count seconds in a minute.

Common mistakes

  • Writing N into a period register that clears synchronously. The timer then counts N + 1 ticks per cycle.

  • Forgetting the counter starts at 0, so N ticks reach a maximum count of N − 1.

Practice Timer

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Timer is taught in Counters.