ENع
←Timers and millis()
Lesson 15 · Interrupts, timers and PWM

Hardware timers, prescalers and millis()

12 min9 steps5 questionsIntermediate
About this lesson

A hardware timer is a counter that the clock drives by itself, so it keeps time while your code does other work. Follow Timer0 on an Arduino Uno: the 16 MHz clock is divided by a prescaler of 64, an 8-bit counter overflows every 1,024 µs, and an interrupt turns those overflows into the millisecond count that millis() returns. Then use millis() to blink an LED without delay(), and see why the 49.7-day wraparound does no harm. The Hardware lesson “Interrupts and I/O: how devices get the CPU's attention” explains why polling wastes time; here you see the firmware side.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 15 · Interactive
01 / 09

A clock, ticking very fast

The chip's clock ticks 16 million times a second. An 8-bit counter fed straight from it would fill up every 16 µs. That is too fast to be useful for counting milliseconds, so we slow the ticks down first.

clock     16,000,000 ticks per second (16 MHz)
one tick  1 / 16 MHz = 0.0625 µs
8-bit     counts 0 .. 255, so 256 ticks fill it
256 x 0.0625 µs = 16 µs: far too short
Loading figure…
or ← →
Read the lesson step by step
  1. A clock, ticking very fast

    The chip's clock ticks 16 million times a second. An 8-bit counter fed straight from it would fill up every 16 µs. That is too fast to be useful for counting milliseconds, so we slow the ticks down first.

    clock     16,000,000 ticks per second (16 MHz)
    one tick  1 / 16 MHz = 0.0625 µs
    8-bit     counts 0 .. 255, so 256 ticks fill it
    256 x 0.0625 µs = 16 µs: far too short
  2. The prescaler divides by 64

    A prescaler is a divider in front of the timer. The Arduino core sets it to 64: one tick passes for every 64 clock ticks. So the timer gets 250,000 ticks a second, one every 4 µs.

    prescaler  64   (wiring.c: "set timer 0 prescale factor to 64")
    choices    1, 8, 64, 256, 1024  (Timer0, datasheet)
    16,000,000 / 64 = 250,000 ticks per second
    one timer tick = 4 µs
  3. The counter counts by itself

    Each slowed tick adds 1 to TCNT0, Timer0's 8-bit counter register. This is hardware: no code runs to count, so the CPU stays free to run your program. It counts 0, 1, 2 ... up to 255.

    TCNT0   Timer0 counter register, 8 bits
    +1 every 4 µs, done by hardware
    0, 1, 2, ... 255
    the CPU runs your code meanwhile
  4. 255, then back to 0

    After 255 the counter rolls over to 0. That is an overflow, and it sets a flag bit, TOV0. It happens every 256 × 4 µs = 1,024 µs, slightly more than one millisecond.

    255 + 1  ->  0     overflow
    TOV0 = 1          the overflow flag
    period  256 x 4 µs = 1,024 µs = 1.024 ms
  5. The flag calls an interrupt

    The core enabled the overflow interrupt, so the flag makes the CPU pause and run a short function, an ISR. It adds 1 to ms and 3 to fract. Hardware clears the flag, and your program carries on.

    ISR     interrupt service routine
    TOV0 -> CPU jumps to TIMER0_OVF_vect
    line 2  ms += 1;  fract += 3;
            ms = 1, fract = 3
    TOV0 cleared by hardware, loop() resumes
  6. Catching up the extra 24 µs

    Each overflow is 1,024 µs, not 1,000. fract keeps the extra 24 µs, in steps of 8 µs, so adds 3. When it reaches 125, a whole millisecond has built up: ms gets one more. Here 41 becomes 43.

    extra   1024 - 1000 = 24 µs = 3 x 8 µs
    limit   125 x 8 µs = 1000 µs
    before  ms = 41, fract = 123   (overflow 41)
    ISR     fract 123 + 3 = 126 >= 125
            fract = 1, ms = 41 + 1 + 1 = 43
    check   42 x 1.024 ms = 43.008 ms
  7. millis() reads the count

    millis() just returns ms. ms is 4 bytes, and the ISR could change it halfway through a read, so millis() turns interrupts off for that copy. The lesson "volatile and sharing data with an ISR" explains why.

    line 1    now = millis();
    millis()  save SREG          (SREG = status register, holds the interrupt on/off bit)
              cli()              (clear interrupts: interrupts off)
              m = timer0_millis  4-byte copy
              restore SREG       interrupts back on as before
              return m
  8. Blink without waiting

    loop() checks the time and moves on. When now - last reaches 500, it flips the LED and adds 500 to last. No delay(), so the rest of loop() keeps running between blinks.

    line 2  500 - 0 >= 500   true
    line 3  last = 500
    line 5  pin 13 HIGH, LED on
    next    true again at 1000 ms
    
    // Arduino Uno R3: blink the LED on pin 13 every 500 ms, no delay()
    unsigned long last = 0;
    bool led = false;
    
    void setup() {
      pinMode(13, OUTPUT);
    }
    
    void loop() {
      unsigned long now = millis();
      if (now - last >= 500) {
        last += 500;
        led = !led;
        digitalWrite(13, led);
      }
      // ... other work runs here, never blocked
    }
  9. After 49.7 days, it wraps

    ms is an unsigned long, 32 bits, so after 2³² ms, about 49.7 days, it rolls back to 0, like TCNT0 does. now - last still works: unsigned subtraction wraps too, so 204 - 4,294,967,000 gives 500.

    unsigned long   32 bits, 0 .. 4,294,967,295
    2^32 ms = 4,294,967.296 s = 49.7 days
    last = 4,294,967,000
    now  = 204            (after the wrap)
    now - last = 500   (mod 2^32): still correct
    but: if (now >= last + 500) breaks at the wrap

Quiz Unlocks after the last step.