#define _XTAL_FREQ 4000000
#include <htc.h>
/* XTAL Oscillator
* Watchdog timer OFF
* Power up timer OFF
* Code protection OFF
*/
__CONFIG(FOSC_XT & WDTE_OFF & PWRTE_OFF & CP_OFF);
int TMR0_CK=0; // here I'll count how many TMR0 CKs have been generated
char cnt=0; // Here I count, every 32 TMR0 CKs, how many seconds have passed
void main(void){
// Intializing ports as outputs, and port value 0
TRISA=0x00;
TRISB=0x00;
PORTA=0x00;
PORTB=0x00;
// Interrupts {GIE=1, T0IE=1}
INTCON=0xA1; // | GIE=1 | EEIE | T0IE=1 | INTE | RBIE | T0IF | INTF | RBIF |
// Prescaler assignment: TMR0
// Prescaler value: (bin) 100 -> 1/32
// Human translated: 1 TMR0 CK is generated every 31250 main XTAL clocks ( (4MHz/4)/32 )
OPTION_REG=0x84; // | RBPU | INTEDG | T0CS | T0SE | PSA=0 | PS2=1 | PS1=0 | PS0=0 |
// The code runs from the interrupt routine from now on,
// it will count clocks and update PORTB value
// the counters and other intructions will take up a few cycles
// but they're actually very few, not really important
}
void interrupt T0ISR(){
if (T0IF){ // TMR0 CK has been generated (TMR0 overflow)
TMR0_CK++; // Update TMR0 CK counter
if (TMR0_CK == 32){
// We reached 1s
// 32*31250 = 1MHz = 1s
// Resetting TMR0 CK counter
TMR0_CK=0;
// Updating the output
PORTB = cnt++;
}
// Releasing interrupt
T0IF=0;
}
}