UNIT 08 · INTERACTING WITH HARDWARE
Clocks and Timers
Every microsecond, counted by hardware.
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.
The unit in six ideas
- 1Chips boot on a fast-starting, inaccurate internal oscillator, then run from a crystal reference multiplied by a PLL.
- 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)).
- 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.
- 4A timer’s update interrupt is exactly periodic; drift appears when software restarts timing from “now”.
- 5Input capture copies the counter at the edge in hardware, so software latency does not affect the measurement.
- 6Duty D = level / (TOP + 1), frequency f_clk / (DIV × (TOP + 1)), average D × VDD; all channels of one counter share the frequency.
Lessons
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?
Counters, Prescalers, and Timer Periods
How do you get from a clock to exactly the period you want?
Measuring Elapsed Time and Handling Wraparound
How do you make time arithmetic correct at that moment too?
Periodic Events and Output Compare
How do you make things happen at exact times, over hours and to the microsecond?
Measuring Pulses with Input Capture
How can the timer itself tell you exactly when each edge happened?
Pulse-Width Modulation and Duty Cycle
How fast, how finely, and what does the signal look like?