Blink without delay using PIC16F877A Timer2 module and CCS C
Related topics:
PIC16F877A Timer0 module and interrupt with CCS C compiler
PIC16F877A Timer1 module and interrupt with CCS C compiler
Timer2 is an 8-bit timer with a prescaler and a postscaler. It can be used as the PWM time base for the PWM mode of the CCP module(s). The TMR2 register
is readable and writable and is cleared on any device Reset.
The input clock (FOSC/4) has a prescale option of 1:1, 1:4 or 1:16, selected by control bits
T2CKPS1:T2CKPS0 (T2CON<1:0>).
The PIC16F877A Timer2 module has an 8-bit period register, PR2. Timer2 increments from 00h until it matches PR2 and then resets to 00h on the next increment cycle. PR2 is a readable and writable register. The PR2 register is initialized to FFh upon Reset.
The match output of TMR2 goes through a 4-bit postscaler (which gives a 1:1 to 1:16 scaling inclusive) to generate a TMR2 interrupt (latched in flag bit, TMR2IF (PIR1<1>)).
Timer2 can be shut-off by clearing control bit, TMR2ON (T2CON<2>), to minimize power consumption.
PIC16F877A Timer2 interrupt example:
This is a simple example which uses Timer2 interrupt to make an LED connected to RB0 blinking at a frequency of 1Hz.
In this example the PIC16F877A microcontroller runs with 4MHz crystal oscillator.
PIC16F877A Timer2 interrupt example C code:
The C code below was tested with CCS C compiler version 5.051.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // PIC16F877A Timer2 interrupt // Timer2 is used to interrupt every 49.93ms http://simple-circuit.com/ #include <16F877A.h> #use delay(crystal=4000000) byte i; #INT_TIMER2 void timer2_isr(void) { clear_interrupt(INT_TIMER2); i++; if(i > 9) { i = 0; output_toggle(PIN_B0); } } void main() { setup_timer_2 (T2_DIV_BY_16, 0xF0, 13 ); // Timer2 prescaler 16, Preload value 0xF0 and postoscaler 13 clear_interrupt(INT_TIMER2); // Clear Timer2 interrupt flag bit enable_interrupts(INT_TIMER2); // Enable Timer2 interrupt enable_interrupts(GLOBAL); // Enable global interrupts output_low(PIN_B0); while(TRUE) ; // Endless loop } |
Reference:
PIC16F877A datasheet from Microchip
Discover more from Simple Circuit
Subscribe to get the latest posts sent to your email.
Why compiler shows ‘undefined identifier — enable_interrupt’ on compileing time??