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

#include <xc.h>

#define FOR_PRESS   0
#define FOR_RELEASE 1

int button_1_state = FOR_PRESS;
int button_2_state = FOR_PRESS;
int button_3_state = FOR_PRESS;

int is_button_1_pressed(void)
{
    if (button_1_state == FOR_PRESS && PORTAbits.RA3 == 0) {
      // we are checking ``PRESS'' and RA3 has been pressed
      button_1_state = FOR_RELEASE;
      return 1;
    }
    else if (button_1_state == FOR_RELEASE && PORTAbits.RA3 == 1) {
      // we are checking ``RELEASE'' and RA3 has been released
      button_1_state = FOR_PRESS;
    }
    return 0;
}

int is_button_2_pressed(void)
{
    if (button_2_state == FOR_PRESS && PORTAbits.RA2 == 0) {
      // we are checking ``PRESS'' and RA3 has been pressed
      button_2_state = FOR_RELEASE;
      return 1;
    }
    else if (button_2_state == FOR_RELEASE && PORTAbits.RA2 == 1) {
      // we are checking ``RELEASE'' and RA3 has been released
      button_2_state = FOR_PRESS;
    }
    return 0;
}

int is_button_3_pressed(void)
{
    if (button_3_state == FOR_PRESS && PORTCbits.RC2 == 0) {
      // we are checking ``PRESS'' and RA3 has been pressed
      button_3_state = FOR_RELEASE;
      return 1;
    }
    else if (button_3_state == FOR_RELEASE && PORTCbits.RC2 == 1) {
      // we are checking ``RELEASE'' and RA3 has been released
      button_3_state = FOR_PRESS;
    }
    return 0;
}

#define MAX 100000

void main(void)
{
    long count = 0;
    // ... set-up ports by TRIS registers
    TRISAbits.TRISA3 = 1;
    TRISAbits.TRISA2 = 1;
    TRISCbits.TRISC2 = 1;
    TRISBbits.TRISB0 = 0;
    TRISBbits.TRISB1 = 0;
    TRISBbits.TRISB2 = 0;
    TRISBbits.TRISB5 = 0;
    LATBbits.LATB0 = 1;
    for (;;) {  // loop forever
        if (is_button_1_pressed()) LATBbits.LATB0 = !LATBbits.LATB0;
        if (is_button_2_pressed()) LATBbits.LATB1 = !LATBbits.LATB1;
        if (is_button_3_pressed()) LATBbits.LATB2 = !LATBbits.LATB2;
        ++count;
        if (count == MAX) {
            LATBbits.LATB5 = !LATBbits.LATB5;
            count = 0;
        }
    }
}
