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

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

unsigned char TON_low[2] =  {0x75, 0xfb};
unsigned char TON_high[2] =  {0xfe, 0xff};

unsigned char TOFF_low[2] = {0xfb, 0x75};
unsigned char TOFF_high[2] = {0xff, 0xfe};

int main(int argc, char** argv) {
    char light_set;
    int tval;
    
    light_set = 0;
    
    TRISBbits.TRISB0 = 0; // output
    TRISAbits.TRISA2 = 1; // input
    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 = 0b011; // prescaler 1:16 ('0b' is a prefix for binary)
    
    TMR0H = TON_high[light_set];
    TMR0L = TON_low[light_set];
    
    INTCONbits.T0IF = 0;
    T0CONbits.TMR0ON = 1; // start the timer
    
    LATBbits.LATB0 = 0; // Turn on initially the LED
    
    for (;;) {
        while (INTCONbits.T0IF != 1) {} 
        TMR0H = TOFF_high[light_set];
        TMR0L = TOFF_low[light_set];
        INTCONbits.T0IF = 0;
        LATBbits.LATB0 = 1; // Turn off the LED
                
        while (INTCONbits.T0IF != 1) {} 
        TMR0H = TON_high[light_set];
        TMR0L = TON_low[light_set];
        INTCONbits.T0IF = 0;
        LATBbits.LATB0 = 0; // Turn on the LED                
        
        if (PORTAbits.RA3 == 0) light_set = 0;
        else if (PORTCbits.RC2 == 0) light_set = 1;
        
    }

    return (EXIT_SUCCESS);
}

