15.2.3 Example: Demo Application with Multiple Vector Tables

This example demonstrates switching between two vector tables with a debugger. Set breakpoints in function main() and examine the contents of variables table1_count and table2_count.

#include <xc.h>

int table1_count = 0;
int table2_count = 0;

extern void (**_ivt_2)(void)  __attribute__((far));

void timer1_init(void) {
  
    T1CONbits.TON = 0; // Stop the timer

    PR1 = 0xFFFF; // Set the period register to maximum value
    TMR1 = 0x00; // Clear the timer register (TMR1)
    IFS1bits.T1IF = 0; // Clear the timer interrupt flag
    IEC1bits.T1IE = 1; // Enable the timer interrupt

    T1CONbits.TON = 1; // Start the timer
}

void __attribute__((__interrupt__, no_auto_psv)) _T1Interrupt(void) {
    IFS1bits.T1IF = 0; // Clear the timer interrupt flag
    table1_count++;
}

void __attribute__((__interrupt__, no_auto_psv)) _T1Interrupt_2(void) {
    IFS1bits.T1IF = 0; // Clear the timer interrupt flag
    table2_count++;
}

int main(void) {
  
  timer1_init();
  while (table1_count < 8) {}
  
  __builtin_setIVTBASE(&_ivt_2); /* switch to IVT '2' */

  while (table2_count < 64) {}

  return 0;
}