PIC Timer2

PIC Timer2
Çeşme:
http://www.exploreembedded.com/wiki/PIC18F4520_Timer.
  1. PIC16F877A
// PIC16F877A Configuration Bit Settings // 'C' source line config statements // CONFIG #pragma config FOSC = HS // Oscillator Selection bits (LP oscillator) #pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled) #pragma config PWRTE = ON // Power-up Timer Enable bit (PWRT enabled) #pragma config BOREN = OFF // Brown-out Reset Enable bit (BOR disabled) #pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming) #pragma config CPD = ON // Data EEPROM Memory Code Protection bit (Data EEPROM code-protected) #pragma config WRT = HALF // Flash Program Memory Write Enable bits (0000h to 0FFFh write-protected; 1000h to 1FFFh may be written to by EECON control) #pragma config CP = OFF // Flash Program Memory Code Protection bit (All program memory code-protected) // #pragma config statements should precede project file includes. // Use project enums instead of #define for ON and OFF. #include <xc.h> #define SBIT_T2CKPS1 1 char value = 0; int count = 0; void interrupt isr() { if(PIR1bits.TMR2IF==1) { TMR2 = 101; /*Load the timer Value, (Note: Timervalue is 101 instead of 100 as the Timer2 needs two instruction Cycles to start incrementing TMR2 */ /* 1 = TMR2 to PR2 match occurred (must be cleared in software) 0 = No TMR2 to PR2 match occurred */ PIR1bits.TMR2IF=0; // Clear timer interrupt flag if(count>=2000) //500us * 2000=1000000us=1sec { count=0; value=~value; // complement the value for blinking the LEDs } else { count++; // Keep incrementing the count till it reaches 2000 to generate 1sec delay } } } void main() { TRISD = 0x00; //COnfigure PORTD as output to blink the LEDs T2CON = (1<<SBIT_T2CKPS1); // Timer2 with external freq and 16 as prescalar TMR2 = 100; // Load the timer value for 500us delay /* Enable timer interrupt bit in PIE1 register 1 = Enables the TMR2 to PR2 match interrupt 0 = Disables the TMR2 to PR2 match interrupt */ PIE1bits.TMR2IE=1; /* 1 = Enables all unmasked interrupts 0 = Disables all interrupts */ INTCONbits.GIE = 1; /* 1 = Enables all unmasked peripheral interrupts 0 = Disables all peripheral interrupts */ INTCONbits.PEIE = 1; /* 1 = Timer2 is on 0 = Timer2 is off */ T2CONbits.TMR2ON = 1; while(1) { PORTD = value; } }