Electronic – PIC: how to set timer0 to give an interrupt at every 1 sec

interruptsmicrocontrollerpictimer

I am programming a PIC18F67K22 and I've set it to use a 16X4Mhz Internal RC oscillator with PLL enabled.

  • High level interrupt on TIMER0 overflow
  • I am using MCC18 compiler.

So how to set TIMER0 to give an interrupt at every second?

Best Answer

The TIMER0 is a 16bits timer, so to set to interrupt every 1 second you need to set:

  • Prescaler @ 16

  • TMR0 Preload @ 3036

The equation:

$$T = \left(\frac{4}{Fosc}\right) \cdot Presc \cdot (Resolution - Preload)$$

Where:

  • T = Period = 1s
  • Fosc = Oscilator Frequency = 4MHz
  • Presc = Prescaler = 16
  • Resolution = 216 = 65535
  • Preload = 3036

Sample code:

// Timer0 Registers:16-Bit Mode; Prescaler=1:16; TMRH Preset=$BD; 
//                  TMRL Preset=$DC; Freq=1,00Hz; Period=1,00 s
T0CON.TMR0ON = 1;  // Timer0 On/Off Control bit: 1=Enables Timer0 / 0=Stops Timer0
T0CON.T08BIT = 0;  // Timer0 8-bit/16-bit Control bit: 1=8-bit timer/counter / 0=16-bit timer/counter
T0CON.T0CS   = 0;  // TMR0 Clock Source Select bit: 0=Internal Clock (CLKO) / 1=Transition on T0CKI pin
T0CON.T0SE   = 0;  // TMR0 Source Edge Select bit: 0=low/high / 1=high/low
T0CON.PSA    = 0;  // Prescaler Assignment bit: 0=Prescaler is assigned; 1=NOT assigned/bypassed
T0CON.T0PS2  = 0;  // bits 2-0  PS2:PS0: Prescaler Select bits
T0CON.T0PS1  = 1;
T0CON.T0PS0  = 1;
TMR0H = $BD;        // preset for Timer0 MSB register
TMR0L = $DC;        // preset for Timer0 LSB register