/* 
 * File:   dimmer_led_2.c
 * Author: corrado
 */

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

#define TIME_ON     5
#define TIME_OFF    250

#define OFF   0
#define ON    1

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

    char state;

    TRISBbits.TRISB0 = 0; // output
    TRISBbits.TRISB1 = 0; // output
    TRISBbits.TRISB2 = 0; // output
    TRISBbits.TRISB3 = 0; // output
    TRISBbits.TRISB4 = 0; // output
    TRISBbits.TRISB5 = 0; // output

    T2CONbits.TMR2ON = 0; // stop the timer
    T2CONbits.T2CKPS = 0b10; // 1:16 prescaler
    T2CONbits.T2OUTPS = 0b0000; // no postscaler
    TMR2 = 0; // reset timer
    PR2 = TIME_OFF; // load period register
    PIR1bits.TMR2IF = 0; // reset interrupt flag
    T2CONbits.TMR2ON = 1; // start the timer
    state = OFF;

    LATB = 0xff; // all leds off

    for (;;) {
        if (PIR1bits.TMR2IF == 1) { // period match
            if (state == OFF) {
                LATB = 0xc0; // all leds on
                PR2 = TIME_ON; // load period register
                state = ON;
            }
            else {
                LATB = 0xff; // all leds off
                PR2 = TIME_OFF; // load period register
                state = OFF;
            }
            PIR1bits.TMR2IF = 0; // reset interrupt flag
        }
    }
    return (EXIT_SUCCESS);
}

