Setup PIC Timer with Interrupt Example (18F Family, MikroC)

software development on PIC microcontroler

Setting up a PIC timer to the correct frequency can be a tricky business for the uninitiated Software Engineer (i.e. Me). So I was pretty happy when I came across this great on-line tool whereby you just type in your oscillator frequency and desired interrupt rate and it generates the setup code for you!

For example I have an 8Mhz clock and wanted a 1KHz interrupt on Timer0, I punched that in and the tool said I should use this set-up code:

//
T0CONbits.T08BIT = 0;
T0CONbits.T0CS = 0;
T0CONbits.PSA = 0;
T0CONbits.T0PS2 = 1;
T0CONbits.T0PS1 = 0;
T0CONbits.T0PS0 = 0;
TMR0H = 0xB;
TMR0L = 0xDC;
T0CONbits.TMR0ON = 1;
//

Happy days!

Now there is a little more to defining the software interrupt handler and enabling the interrupt so I have included the code for a slightly more verbose example that configures and enables Timer0 via mikroC on the PIC18F25K22:

//
void init_timers();
void main() {
  init_timers();
  for (;;) {
    // do something...
  }
}
void init_timers() {
  // Initialise Timer0 for a 1Khz interrupt
  // 8Mhz clock & want 1Khz interrupt
  // See http://www.enmcu.com/software/timer0calculatorandcodegeneration
  // for values.
  //
  INTCON.GIE=1;         //globle interrupt enable
  INTCON.PEIE=1;        //peripharel interrupt enable
  INTCON.TMR0IF = 0x0;  //Clear timer0 overflow interrupt flag
  INTCON.TMR0IE = 1;    //enable the timer0 by setting TRM0IE flag
  T0CON.T08BIT = 0;     // 16 Bit timer
  T0CON.T0CS = 0;       // Internal clock
  T0CON.PSA = 1;        // Set scaler to 1:4
  TMR0H = 0xF8;         // Initial count of 0xF830
  TMR0L = 0x30;
  T0CON.TMR0ON = 1;     // Turn Timer0 on.
}
// interrupt handler for the timer0 overflow
void interrupt(void) {
  // http://www.enmcu.com/software/timer0calculatorandcodegeneration
  
  // Reset the timer count
  TMR0H=0xF8;
  TMR0L=0x30;
  
  // Reset interrupt flag
  INTCON.TMR0IF = 0;
  // Do some work here
}
//
3 replies

Comments are closed.