Hi MarkF, may I know whats the different between Compare mode and the way I use to declare?
Why do we need to set it as 25kHz?
You can use any frequency you want.
I just did a quick copy-and-paste from one of my projects as an example. And 25KHz is the interrupt frequency I happened to be using.
Setup the values for the Compare mode and Timer1 Prescaler for the frequency you want.
The Compare Mode watches Timer1 and when it matches, Timer1 is automatically reset to zero and the interrupt called.
Refresh your understanding of the Compare Mode and Timer1 from the datasheet.
By using the Compare Mode, Timer1 is reset in hardware.
Therefore, you don't loose the few clock cycles needed by the ISR routine before being able to reset Timer1 yourself.
In most case, the timing just isn't that critical.
In large projects you may be processing more than one interrupt.
In which case doing it your way, you would want the have the Timer1 processing at the beginning of the ISR.
Neither way is right or wrong. As a programmer, you make that decision on a per project bases.
Or use the compare mode with Timer 1.
Set once and forget.
(Set for 25KHz interrupt. Couldn't be bothered to change the time values.)
if (PIE1bits.CCP1IE && PIR1bits.CCP1IF)
For the code if(PIE1bits.CCP1IE && PIR1bits.CCP1IF) does it means when both are trigger to 1 and it will do the function inside the if ?and using this method we do not need to declare "PIE1bits.CCP1IE ==1&& PIR1bits.CCP1IF==1" inside the condition?
In the interrupt service routine (ISR), you check that the Compare Interrupt is ENABLED and the Flag is SET.
Then, you clear the Flag and do whatever processing you need for the Compare interrupt.
You may also have other interrupts enabled and you need to check each of their enable bits and their flags.
You don't want to apply your Compare Mode processing to the wrong interrupt.
Note: You want to keep the processing inside the ISR routine as short as possible.