/* 
 * File:   tmr0_test_3.c
 * Author: corrado
 *
 * Created on October 18, 2015, 6:18 PM
 */

#include <xc.h>
#include <stdio.h>
#include <stdlib.h>

char c0 = 0, c1 = 0; // why char? because they are 8 bits
char period = 3;

void interrupt isr()
{
    if (INTCONbits.T0IF == 1) { // overflow!
        TMR0 = -15625; // reload timer
        INTCONbits.T0IF = 0; // clear overflow
        ++c0;
        ++c1;
/*        if (c0 == 2) { // flash led 0
            LATBbits.LATB0 = !LATBbits.LATB0;
            c0 = 0;
        }*/
        if (c1 >= period) { // flash led 1
            LATBbits.LATB1 = !LATBbits.LATB1;
            c1 = 0;
        }
    }    
}

int main(int argc, char** argv) {

    TRISBbits.TRISB0 = 0; // output
    TRISBbits.TRISB1 = 0; // output
    TRISAbits.TRISA3 = 1; // input
    TRISCbits.TRISC2 = 1; // input

    T0CONbits.TMR0ON = 0; // stop the timer
    T0CONbits.T08BIT = 0; // timer configured as 16-bit
    T0CONbits.T0CS = 0; // use system clock
    T0CONbits.PSA = 0; // use prescaler
    T0CONbits.T0PS = 0b111; // prescaler 1:256 ('0b' is a prefix for binary)
    TMR0 = -15625; // initial timer value
    INTCONbits.T0IF = 0; // clear the overflow bit initially
    INTCONbits.T0IE = 1; // turn on interrupt generation in TMR0
    T0CONbits.TMR0ON = 1; // start the timer
    
    RCONbits.IPEN = 0; // do not use priorities
    INTCONbits.PEIE = 1; // enable peripheral interrupts
    INTCONbits.GIE = 1; // enable interrupts globally    

    for (;;) {
        
        if (PORTAbits.RA3 == 0) {
            if (period > 1)
                --period;
            while (PORTAbits.RA3 == 0) {}
        }
        
        if (PORTCbits.RC2 == 0) {
            ++period;
            while (PORTCbits.RC2 == 0) {}
        }
        
    }
    return (EXIT_SUCCESS);
}

