UNIT 08 · INTERACTING WITH HARDWARE

Clocks and Timers

Every microsecond, counted by hardware.

6 lessons24 guided experiments41 min full read

Everything a microcontroller does in time, from blinking an LED to sampling audio to generating a motor’s drive signal, comes from a clock and the counters it drives. Get the arithmetic wrong by one and a 1 kHz tick runs at 999 Hz; read a counter in the wrong order and a timestamp jumps by a whole wrap; toggle a pin in software and its edges wander by microseconds. Timers exist so that the hardware, not the software, keeps time.

Start with lesson 1 →

The unit in six ideas

  1. 1Chips boot on a fast-starting, inaccurate internal oscillator, then run from a crystal reference multiplied by a PLL.
  2. 2A timer divides twice: the counter advances every PSC + 1 input cycles and wraps after ARR + 1 counts; f_update = f_clk / ((PSC + 1)(ARR + 1)).
  3. 3A counter extended by an overflow count must be read so both parts belong to one instant: high, low, high again, retrying if the high part changed.
  4. 4A timer’s update interrupt is exactly periodic; drift appears when software restarts timing from “now”.
  5. 5Input capture copies the counter at the edge in hardware, so software latency does not affect the measurement.
  6. 6Duty D = level / (TOP + 1), frequency f_clk / (DIV × (TOP + 1)), average D × VDD; all channels of one counter share the frequency.

Lessons

  1. LESSON 01 · 4 EXPERIMENTS · 7 MIN

    Clock Sources, Dividers, and Clock Trees

    Where do all these frequencies come from, and what happens to the UART when someone changes one of them?

  2. LESSON 02 · 4 EXPERIMENTS · 7 MIN

    Counters, Prescalers, and Timer Periods

    How do you get from a clock to exactly the period you want?

  3. LESSON 03 · 4 EXPERIMENTS · 7 MIN

    Measuring Elapsed Time and Handling Wraparound

    How do you make time arithmetic correct at that moment too?

  4. LESSON 04 · 4 EXPERIMENTS · 6 MIN

    Periodic Events and Output Compare

    How do you make things happen at exact times, over hours and to the microsecond?

  5. LESSON 05 · 4 EXPERIMENTS · 7 MIN

    Measuring Pulses with Input Capture

    How can the timer itself tell you exactly when each edge happened?

  6. LESSON 06 · 4 EXPERIMENTS · 7 MIN

    Pulse-Width Modulation and Duty Cycle

    How fast, how finely, and what does the signal look like?