/*******************************************************
FILE:     lightswitch.c

DESCRIPTION: Use VB program to switch the PICchip LED on and
off. 

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)      // declare clock speed
#use rs232(baud=19200,xmit=PIN_B5,rcv=PIN_B2) // USART


//--Pin definitions

#define LED      PIN_B0   // LED

//--Global variables

int1 hflag;
int8 cmd,data;


/*******************************************************
  Send_data()
  Sends a 2-byte frame to host, 10-bit data, 6-bit cmd.
  Byte 0 has lower 8 bits of data, byte 1 has high 2 bits of
  data and 6 bit cmd. 
*******************************************************/

void send_data(int8 cmd, int16 data) {

  putc(make8(data,0));   
  putc((data >> 8) + (cmd << 2)); 
}

/*******************************************************
  Serial port character receive interrupt service routine
  Incoming data is a 2 byte frame, byte 1 = cmd, byte 2 = data.
*******************************************************/
#int_rda
void serial_isr(void)
{
  cmd = getc();       // get data
  data = getc();
  hflag=1;            // set flag for main program
}

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

void main(void)
{
  int8 i;
  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

  for (i=0;i<2;i++) {
    output_high(LED);
    delay_ms(100);
    output_low(LED);
    delay_ms(300);
  }
  
//-------enable interrupts
                    
  enable_interrupts(INT_RDA);    // receive serial char
  enable_interrupts(GLOBAL);    

//-------loop forever

  while (TRUE) {
   while (!hflag) {}   // do nothing unless host command
    hflag=0;
    switch (cmd) {        // branch on host command
      case 1:             // switch LED
        if(data)
          output_high(LED);
        else
          output_low(LED);
        break;
      case 255:             // are you there?
        send_data(1,1);
        break;
      default:
        break;
    }     
  }
}


