Thursday, March 10, 2016

PIC16F877A Timer1 module and interrupt

Blink without delay using PIC16F877A and CCS C
Related topics:
PIC16F877A Timer0 module and interrupt
PIC16F877A Timer2 module and interrupt  
The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L) which are readable and writable. The TMR1 register pair (TMR1H:TMR1L) increments from 0000h to FFFFh and rolls over to 0000h.
PIC16F877A Timer1 interrupt:
The TMR1 interrupt, if enabled, is generated on overflow which is latched in interrupt flag bit, TMR1IF (PIR1<0>). This interrupt can be enabled/disabled by setting/clearing TMR1 interrupt enable bit, TMR1IE (PIE1<0>).
PIC16F877A Timer1 prescaler rate:
Prescaler rate of the timer1 can be: 1, 2, 4 or 8.
The following equation computes timer1 frequency:
Timer1_freq = MCU_freq / {4 * Prescaler * (65536 - TMR1)}
Where TMR1 is preload value.
And Timer1 overflow time = 1/Timer1_freq
PIC16F877A Timer1 interrupt example:
This is a simple example which uses timer1 interrupt to make an LED connected to RB0 blinking at a frequency of 1Hz.
pic16f877a timer1 interrupt ccs pic c circuit
PIC16F877A Timer1 interrupt example CCS PIC C code:
The timer is used to interrupt every 500ms and to make the LED ON for 500ms and OFF for 500ms. HS oscillator used with frequency of 4MHz.

// PIC16F877A Timer1 interrupt
// Timer1 is used to interrupt every 500ms

#include <16F877A.h>
#use delay(crystal=4000000)

void timer1_isr(void)

void main()
   setup_timer_1 ( T1_INTERNAL | T1_DIV_BY_8 ); // Internal clock and prescaler 8
   set_timer1(3036);                            // Preload value
   clear_interrupt(INT_TIMER1);                 // Clear Timer1 interrupt flag bit
   enable_interrupts(INT_TIMER1);               // Enable Timer1 interrupt

   while(TRUE) ; // Endless loop

PIC16F877A datasheet from Microchip