Timers on DSPics are easy – and after helping a few people out with timers at uni I thought I would post a really quick how-to on setting up a timer to interrupt at a set frequency. First lets start with a few bits you need to know:
Fosc = 40000000;
That’s it
Just make sure that this value is the number in Hz on your oscillator (or a multiple of it if using PLL)
Next its important to remember there are different types of timers on a pic, do some research and rtfm before doing any pic / embedded work – will save you hours, I am using timer 1 – as its the first one in the manual :p
Next bits:
T1CONbits.TCKPS = 0x02; // Select the PRESCALER
TMR1 = 0x00; // Make sure the timer is starting from zero
PR1 = 600; // How long the timer should run before an interrupt (in timer ticks)
_T1IF = 0; // Clear the interrupt flag
_T1IE = 1; // Enable the interrupt
T1CONbits.TON = 1; // Turn the interrupt on
void __attribute__((__interrupt__)) __attribute__((no_auto_psv)) _T1Interrupt(void)
{
// Funky interrupt code goes
}
To explain, the prescale waits x many ticks before incrementing the timer counter and is usually a set number like 1,8,32 or 64. To calculate the number for PR1 you then juse a very simple formula:
[math]Fcy = Fosc/2[/math]
[math]PR1 = (Freq^-1)/(Fcy^-1)[/math]
Where Freq is your desired interrupt frequency. Then just round the value of PR1 to the nearest integer if it is not one already. Simple!
As a side note – more information to why the interrupt function has a no_auto_psv attribute can be found at FlyingPic24.com
Hope this has been useful – please comment if you have any corrections/questions/comments.
-
Categories
-
Meta