Timers Basics
Overview
Timers are peripheral devices used to control the interval between events. In embedded systems design, precise timing is a fundamental requirement. Timers are commonly used in multi-threaded operating systems to determine how long a task runs before switching to another. They can also be used for pulse-width modulation (PWM) to dim LEDs and conserve power, or to set the sampling rate for analog signals. Nearly every embedded software project utilizes timers in some form.Timer Basics
A timer functions as a finite state machine that increments or decrements a register with each clock cycle. All timers include a CURRENT register that holds the current count value and a RELOAD register that sets the timer’s period. While modern microprocessors often include additional registers to control timer behavior, these two are sufficient to understand how timers measure precise durations. Consider a basic timer that decrements the CURRENT register once per clock cycle. The programmer sets the RELOAD register with a desired value, and the timer counts down until the CURRENT register reaches zero. To calculate the elapsed time, you need to know the clock frequency driving the timer. Suppose the clock runs at 50 MHz, meaning one clock cycle takes 20 ns. If the RELOAD register is set to 100,000, the timer period is:20ns×100,000=2ms
Timer Characteristics
Timers can have various modes and features. Here are some common ones:- Direction (Up/Down): A timer can count up from 0 to the RELOAD value or count down from the RELOAD value to 0.
- Periodic: A periodic timer restarts its count after reaching 0, using the RELOAD value. This continues until the timer is disabled.
- One-Shot: A one-shot timer counts for a single period and then stops. It must be manually restarted by software.
- Prescalers:
A prescaler slows the rate at which the timer counts by dividing the clock frequency. For example, with a 50 MHz clock and a prescaler of 3, the timer updates every 4 clock cycles:
20ns×100,000×4=8ms(Note: A prescaler of 0 means the timer counts every cycle; a prescaler of 1 means every other cycle, and so on.)