Using Timers in MPLAB® X with MCC

Using an internal timer on a PIC® MCU is simplified with the MPLAB® Code Configurator (MCC) within MPLAB® X. There are a variety of timers available on a device but the setup within MPLAB IDE is similar for each. This article will focus on the Timer2/4/6 8-bit timers that can be used for a variety of useful applications but they are typically used to run the timing for the Pulse Width Modulation (PWM) module.

Locating the Timer2/4/6 Module

The Timer2 (Timer4 or Timer6) module can be found in the MPLAB® Code Configurator (MCC) under Device Resources.

Figure%201.JPG

Choosing TMR2, TMR4, or TMR6 will open the following window:

Figure%202.JPG

Basic Module Functionality:

Clock Source: This drop down menu gives a multitude of options for clock source inputs. Some sources will give time increments, such as FOSC/4, while others will send pulses that will effectively turn the timer into a counter.

Postscalar: This value changes how often the output of the timer sends an interrupt. This is one method to extend the length of the timer period.

Note that the Postscalar adjustments will not affect the PWM signal if using the Timer2/4/6 for PWM purposes. Always remember to check the notifications and actual period values compared to the PWM values in the PWM module.

Prescalar: This value changes how often the clock edges are recorded to the timer, which is useful for increasing the period of the timer.

Polarity: This menu chooses whether the Timer will count on the rising or falling edge of the input clock cycle.

Clock Sync: The Timer can be set to sync with the system clock by checking the Enable Prescaler Sync and the Enable Clock Sync.

Timer Period: This defines the total cycle length for one clock cycle.

Ext Reset Source: The Timer2/4/6 allows for some external sources to reset the timer should your application use this function. This can be useful for controlling circuits that need to be shut down, or reset, if a certain event happens. For more information, see the datasheet section 29.3.

Control Mode: Timer2/4/6 can run in three modes.

  • Roll Over Pulse is a continuous timer which, once the time has been completed and the timing buffer filled, will automatically restart. This is useful for most basic timing operations.
  • One Shot Mode works similarly to Roll Over Pulse but will only cycle once. Once the value set in the T2PR register is reached, then the T2ON bit must be reset. Finally,
  • Monostable Mode works similarly to one shot, but can be continued through use of an external reset.

Start/Reset Option: This sets the available options to use for starting and stopping the timer, as well as continuing based upon the aforementioned control mode.

Configuring the I/O for an External Timer Signal

Similar to the Timer0 module, generally the Timer2/4/6 is used for internal purposes and does not need external pins. However, should you want to output the clock signal, there are certain ports that will do that as seen below:

Figure3.JPG

Using Basic Software Functionality in main.c file

MCC will generate functions to make using the timers easier. These are placed in the tmrx.h file generated by the MCC
While the functions shown here are based upon using Timer2, functions will be created for whatever timer is selected.

Software Function What it does
void TMR2_Initialize(void); This function is only necessary if the Timer2 is not enabled during initialization, meaning the box Enable Timer was unchecked. This must be called before any other functions are called.
void TMR2_Start(void); If you do not enable the Timer to start, then this must be called after the timer is initialized to physically start the Timer.
void TMR2_Stop(void); Calling this function will stop the operation of Timer2, which could be useful if the Timer is not necessary for part of an application.
uint8_t TMR2_ReadTimer(void); As mentioned above, this timer overflows at the register value dictated by the period. This function allows you to read the timer at any moment in time, which could be useful for reading passages of time or running delays without delaying the whole CPU. This function may also be useful to trigger part of the program at a particular time.
uint8_t TMR2_ReadTimer(void); This function allows you to write a value directly to the TMR2 register. This could be useful when your program uses the Timer to trigger something, and then should restart at a particular time after the trigger has been completed.
void TMR2_LoadPeriodRegister(uint8_t periodVal); This function allows you to change the timer period, which could be particularly useful if your system needs to send different PWM signals at different times. This function will allow the period of your signal to change dynamically.
bool TMR2_HasOverflowOccured(void); Every time the timer reaches your defined period, the bit resets back to 0x00 and restarts counting. This function allows you to watch for that to happen, and then returns TRUE, or 1, every time it occurs.

Example Code

This code also uses GPIO described in another section of this site. In this example the LEDs on the board will blink on for two seconds and then permanently shut them off. The LEDs are configured to Start High and the period is set for 2 s.

#include "mcc_generated_files/mcc.h"
 
/*                         
Main application   
*/
void main(void)
{
 
    SYSTEM_Initialize();    // initialize the device    
 
    TMR2_Initialize();                  //Intialize the TMR2
    TMR2_Start();                       //Start the Timer2
 
    while (1)
    {
        if(TMR2_HasOverflowOccured()){  //Check to see when the Timer's period has been reached via checking the overflow bit  
            TMR2_Stop();                //Stop the Timer so it will no longer overflow
            IO_RA0_Toggle();            //Toggle the states of the 4 LEDs to LOW, or off
            IO_RA1_Toggle();
            IO_RA2_Toggle();
            IO_RA3_Toggle();
        }
 
    }    
}

Summary

Timers are very useful in microcontroller projects and MPLAB X teamed with the MCC makes setting all this up easy and effective to use. These same techniques can be used with MPLAB Xpress and MCC. Here is an example project using a Timer to control PWM.

20th Annual
Microchip MASTERs Conference 2016
Register now - Deadline: July 29

JW Marriott Desert Ridge Resort-Phoenix, AZ

© 2016 Microchip Technology, Inc.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.