/*
 * File:   led_1.c
 * Author: corrado
 *
 * Created on October 23, 2016, 11:16 AM
 */


#include <xc.h>

int is_button_pressed(int current_value, int * prev_state)
{
    int ret_value = 0;
    if (*prev_state != current_value) {
        // ok, the button has changed state!
        if (current_value == 0) {
            // OK!! We have got button press
            ret_value = 1;
        }
        *prev_state = current_value;
    }    
    return ret_value;
}

void main(void)
{
    long count = 0;
    int button_1_state, button_2_state;
    TRISAbits.TRISA3 = 1;
    TRISAbits.TRISA2 = 1;
    TRISBbits.TRISB0 = 0;
    TRISBbits.TRISB1 = 0;
    TRISBbits.TRISB2 = 0;
    LATBbits.LATB0 = 1;
    LATBbits.LATB1 = 1;
    LATBbits.LATB2 = 1;
    button_1_state = PORTAbits.RA3;
    button_2_state = PORTAbits.RA2;
    for (;;) {  // loop forever
        if (is_button_pressed(PORTAbits.RA3, &button_1_state))
            LATBbits.LATB0 = !LATBbits.LATB0; // toggle the led
        if (is_button_pressed(PORTAbits.RA2, &button_2_state))
            LATBbits.LATB1 = !LATBbits.LATB1; // toggle the led
        ++count;
        if (count == 200000) {
            LATBbits.LATB2 = !LATBbits.LATB2; // toggle the led
            count = 0;
        }
    }
}
