/*
 * File:   main.c
 * Author: boos
 *
 * Created on July 4, 2019, 9:10 PM
 */

// CONFIG
#pragma config FOSC = XT        // Oscillator Selection bits (XT oscillator: Crystal/resonator on RA6/OSC2/CLKOUT and RA7/OSC1/CLKIN)
#pragma config WDTE = ON        // Watchdog Timer Enable bit (WDT enabled)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = ON       // RA5/MCLR/VPP Pin Function Select bit (RA5/MCLR/VPP pin function is MCLR)
#pragma config BOREN = ON       // Brown-out Detect Enable bit (BOD enabled)
#pragma config LVP = OFF        // Low-Voltage Programming Enable bit (RB4/PGM pin has digital I/O function, HV on MCLR must be used for programming)
#pragma config CPD = OFF        // Data EE Memory Code Protection bit (Data memory code protection off)
#pragma config CP = OFF         // Flash Program Memory Code Protection bit (Code protection off)

#include <xc.h>

// LED is connected to RB3
#define LED RB3

// global buffer variable
int buffer = 0;

// main function
void main (void) {

    // LED is a digital OUTPUT
    TRISB3 = 0;
    
	// TIMER0 works with 1/4 of the internal clock
    // (that amounts to 1.048576 MHz)
	T0CS = 0;

	// set the TIMER0 prescaler to 1:1
	PSA = 1;
	PS0 = 1;
	PS1 = 1;
	PS2 = 1;

	// create an interrupt when TIMER0 overflows
	T0IE = 1;

    // enable interrupts
	GIE = 1;
    
    // main loop
    while (1) {
        
        // and yes, nothing happens here!

    }
    
    return;
}

// the interrupt service routine
void __interrupt () isr (void) {    

    // has TIMER0 reached its maximum?
	if (T0IF) {
        
        // increase the buffer variable
        // whenever TIMER0 overflows
        buffer++;
        
        // has it overflown 4096 times?
        // then one second has passed!
        if (buffer >= 4095) {
            
            // reset buffer
            buffer = 0;
            
            // toggle LED
            if (LED) {
                LED = 0;
            } else {
                LED = 1;
            }
            
        }
        
		// IMPORTANT: reset the interrupt flag!
		T0IF = 0;

	}

}