PIC32-MX Using Timer 2

This page shows simple initialisation & use of a PIC32-MX Type B timer in 16bit mode

Refer PIC32-MX Family Reference Manual Sect 14 Timers found here (opens in new window)

Parameters:

  • Peripheral clock (80MHZ in our case)
  • TnCONBits.TCKPS prescaler
    • 1/1 - 1/256 in our case
  • PRn (max 16bits = 65535)

Goal: Interrupt every millisecond, ie 1,000 timer per second

Summary of timer operation: (given a peripheral clock of 80MHZ and a prescaler of 1/8):

  • For every peripheral clock / 8, increments TMRn
  • When TMRn = PRn:
    • Sets TMRn back to 0
    • Calls the interrupt

Calculating PRn:

In effect, the combination of the peripheral clock and prescaler give us our possible range of time between interrupts.  We then use PRn to select where within that range when to generate the interrupt:

  • minimum = peripheral clock / prescaler / PRn = 80,000,000 / 8 / 1 = 10,000,000 interrupts per second
  • maximum = peripheral clock / prescaler / PRn = 80,000,000 / 8 /65535 = ~15.26 interrupts per second

We want to fire our interrupt 1,000 times second,  so to calculate our PRn setting:

  • minimum / required interrupts per second = PRn setting = 10,000,000 / 1,000 = 10,000

Initialise the timer:

	// Use Timer 2 16bit
	// Triggers interrupt: peripheral clock / prescaler / PR2 = 1000 times per second
	// Triggers interrupt: 80,000,000 / 8 / 10000 = 1000 times per secon
	T2CON = 0x0;			//Turn it all off, also T2 as 16bit timer
	T2CONbits.TCKPS = 11; 	// 1:8 prescale
	// Base
	PR2 = 10000ul;
	// Clear counter
	TMR2 = 0;

	IPC2bits.T2IP = 1;	// Interrupt priority 1 (low)
	IFS0CLR = _IFS0_T2IF_MASK;
	IEC0SET = _IEC0_T2IE_MASK;

	T2CONbits.TON = 1;		// Turn it on

Interrupt service function:

//T2 interrupt handler
void __attribute((interrupt(ipl1), vector(_TIMER_2_VECTOR), nomips16)) _T2Interrupt(void)
{
	// --Your code here
	// Reset interrupt flag
	IFS0CLR = _IFS0_T2IF_MASK;
	// --Or your code here if < time between interrupts but be careful..
}