8-Bit PIC® MCU Timers

Last modified by Microchip on 2023/11/09 09:03

Timers and counters are very useful, and some may say required, features of the PIC® MCU. As the name implies, timers indicate when an amount of time has elapsed. Timers can also count using the same internal registers. The difference between a timer and a counter is the source of the pulse that increments the counting register. If the source is time-based, such as the oscillator clock that runs the microcontroller, then it is a timer. If the source is a pulse from a sensor or switch then it is a counter. Through most documentation, the timer/counter peripheral is typically referred to as a timer peripheral (even though it can also count).

Counting and timing become the basis for many other features in the PIC MCU. Controlling the brightness of LEDs can be completed with a Pulse Width Modulation (PWM) signal. That PWM signal is based on a timer. Creating a people counter at an amusement park or subway entrance can be based on a digital display and a counter.

At the heart of the timer/counter is a binary counter register that increments by one on every input signal. The size of that counter determines the number of pulses it will accept until it overflows and resets back to zero. The 8-Bit PIC MCU devices have both 8-bit (256 pulses to overflow) and 16-bit (65535 pulses pulse to overflow) timers. When counting a pulsed input these may be large enough but when the internal instruction clock can run in the megahertz (million pulses per second) range, then those overflow values become quite small.

Below is a simplified block diagram of the Timer0 module:

timer0 block diagram

A timer can be expanded by adding a Prescaler. Prescaling is simply a second counter placed in front of the main counter to skip a number of clock pulses. The prescaler is essentially a counter with an adjustable overflow value. The prescaler can be set to overflow at values of 2, 4, 8 … up to 256 pulses. For example, if the prescaler is set to eight then the timer counter will receive one pulse after every eight clock pulses. This allows the designer to extend the time before getting the overflow pulse from the timer/counter.

It is the overflow pulse that is the key to the operation. That overflow pulse feeds other peripherals, such as the interrupt structure, within the PIC MCU. When the overflow occurs, the interrupt vector address is triggered and a separate software routine called the Interrupt Service Routine (ISR), is implemented separately from the main program loop. Timer overflows can also trigger Analog-to-Digital Conversions (ADC). The overflow can also simply indicate that a correct number of pulses have been received or a specified amount of time has elapsed.