Timers on 16-bit MCUs
Timer Overview
Simplified Timer Block Diagram
Operation
Timers on 16-bit MCUs can be driven by one of two inputs:
- Tcs - the MCU's internal clock
- TxCK pin connected to either an asynchronous signal or to a clock source.
Tcs Input
In Timer mode, the timer is driven by the internal clock (Tcs). The TMRx register contains the current value of the timer. When a timer is turned on (TCON = 1), the time increments at a frequency determined by the speed of Tcs and the timer's prescaler settings. The value of TMRx increments until it equals the ((PRx)). When TMRx equals PRx, three things happen:
- TMRx is reset to 0. The timer continues operating incrementing TMRx at regular intervals.
- The interrupt request flag ( TxIF) is set to one.
- If the timer's interrupt is enabled and the priority assigned to the timers is sufficient (see the "Exception Handling on a 16-bit PIC® MCU" page) an interrupt will occur sending program control to the assigned interrupt service routine.
TxCK Input
Timers can be driven by either an asynchronous signal or clock on the TxCK pin. Using the Gate Synch facility a timer can be set to count the number of timers the TxCK pin is toggled. This can be useful when TxCK is driven by an external asynchronous signal. In addition to generating an interrupt when the count equals the value loaded into PRx, the timer gate can generate an interrupt request upon each falling edge of TxCK.
Timer Initialization
Each 16-bit MCU timer has one control register TxCON, a period register PRx, and a timer value register TMRx ( where x = the "number" of the timer)
- TMRx is the value of the timer. Application programs typically load a value into this register at initialization to ensure the first timer period is of a known time.
- PRx defines the timer period of the timers. The value loaded into the PRx determines the time interval between matches of TMRx and PRx. When driven by Tcs, the period of a timer is a product of the Tcs, the pre-scaler value, and PRx. The value loaded into PRx can be calculated manually, but most people find using MPLAB® Code Configuration (MCC) to be a better option. See the following code example to see how MCC is used to calculate PRx.
- TxCON configures the clock source and the prescaler to the timer. TxCON provides the ability to start or stop the timer.
bit 15 | TON: Timer x On bit 1 = Timer x is Enabled |
bit 13 | TSIDL: Timer stops in Idle mode bit 1 = Timer x stops when MCU enters Idle mode |
bit 9-8 | TECS<1:0>: Timer x Extended Clock Source Select bits (useed when TCS = 1) 11 = Generic Timer (TMRCLK) external pin |
bit 6 | TGATE: Timer x Gated Time Accumulation Enable bit 1 = Timer Gate Accumulation Enabled |
bit 5-4 | TCPS<1:0>: Timer x Input Clock Prescaler select bits 11 = 1:256 |
bit 3 | T32: 32-bit Timer Select mode bit 1 = Timer x joins with Timer y to form 1 32-bit timer |
bit 1 | TCS: Timer x Clock Source select bit 1 = Timer x source selected by TECS<1:0> |