I have a peculiar problem with the timer on the DSPIC33F. I need to create a delay function and I have decided to use Timer 2 to count the number of instruction cycles. The function would enable the timer and then wait in the while loop waiting for the interrupt flag to be set. See code below:
T2CONbits.TON = 0; // disable Timer 2
IFS0bits.T2IF = 0; // reset Timer 2 interrupt flag
TMR2 = 0; // reset timer accumulator
T2CONbits.TON = 1; // enable Timer 2
while(!IFS0bits.T2IF); // Wait until until the timer 2 timeout
IFS0bits.T2IF = 0; // reset Timer 2 interrupt flag
T2CONbits.TON = 0; // disable Timer 2
The function works perfectly fine if the TMR2 interrupts are disabled. However, if the TMR2 interrupts are enabled, the firmware restarts when the interrupt flag is set. This restart only happens when I run through the code, but not during the step-by-step execution (I am using the ICD3 with MPLab 8.something). I did not setup the ISR for TMR2. All other interrupts are disabled.
Even though I have achieved my goal of creating the delay function, I am still wondering about the possible reasons for the firmware restart. Is that because for some reason I can address the interrupt flag only inside the ISR? Or are there any other reasons?