/*******************************************************
FILE:     led_switch-2.c

DESCRIPTION: Switch controlled LED. Complex logic. 

REVISION HISTORY:
*******************************************************/
//--Includes

#include <16f88.h>

//--Setup commands

#fuses INTRC_IO,NOWDT,NOPROTECT,PUT,NOWRT,NOLVP  // internal oscillator
#id 0x1234                     // 4 digit id
#use standard_io(A)
#use standard_io(B)
//#use fast_io(A)
//#use fast_io(B)
#use delay(clock=8000000)      // xx MHz resonator



//--Pin definitions


#define LED      PIN_B0   // LED
#define BUTT     PIN_B1   // switch

//--Global variables


//--Utility functions

void flash(int n) {
  int i;
  for (i=0;i<n;i++) {
    output_high(LED);
    delay_ms(100);
    output_low(LED);
    delay_ms(300);
  }
}
/****************************************************
Button checking function. If button up, returns false.
If button down, waits for button up and returns true.
****************************************************/

BOOLEAN butt_check(void)
{
  if (!input(BUTT)){          //if button pressed
    delay_ms(20);             // for debounce
    while (!input(BUTT)) // wait for button up
      ;
    delay_ms(5);               // for debounce
    return(TRUE);
  }
  else
    return(FALSE);
}


/*******************************************************
  Main starts here
*******************************************************/

void main(void)
{
  int1 on_flag;
  
  setup_oscillator(OSC_8MHZ);

//-------Set direction registers

//  set_tris_a(0xFF);   // a is all inputs (for adc)
//  set_tris_b(0xC0);   // b7,b6 in, rest out


//-------Flash led a few times

  flash(5);
  on_flag=0;

//-------Endless loop dealing with LED and switch

  do {
    if (butt_check()) {
      if (!on_flag) {
        output_high(LED);  //led on
        on_flag=1;
      }
      else {
        output_low(LED);
        on_flag=0;
      }
    }

  } while (TRUE);
}
