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

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

int main(int argc, char** argv) {
    char c0 = 0, c1 = 0; // why char? because they are 8 bits

    TRISBbits.TRISB0 = 0; // output
    TRISBbits.TRISB1 = 0; // output

    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
    T0CONbits.TMR0ON = 1; // start the timer

    for (;;) {
        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 == 3) { // flash led 1
                LATBbits.LATB1 = !LATBbits.LATB1;
                c1 = 0;
            }
        }
    }
    return (EXIT_SUCCESS);
}

