#include <pic.h>
#include	"delay.h"

__CONFIG(WDTDIS & PWRTEN & MCLRIO & BORDIS & LVPDIS & INTIO);

static unsigned char	xmsec;
static unsigned char	key;

void setup_port() {

	CMCON	= 0b00000111;
	TRISA	= 0b00000000;
	TRISB	= 0b11110010;
	PORTA	= 0b00000000;
	PORTB	= 0b00000000;
	OPTION	= 0b10000111;
	OSCF = 1;

	SPBRG	= 0x19;
	TXSTA	= 0b00100100;
	RCSTA	= 0b10010000;

	TMR0	= -PRELOAD;		// preload timer
	T0IE	= 1;
	GIE	= 1;			//interrupt enable

}

unsigned char switch_read() {

	return(~PORTB&0xF0>>4);
}


static void interrupt intx(void) 
{
	if(T0IF == 1){
	  xmsec++;
	  TMR0 += -PRELOAD;	// re-load timer
	  T0IF = 0;	
	}
}

void send(data)
  unsigned char	data;
{
	TXREG	= data;
	while (!TRMT) ;
}

void sends(line)
  unsigned char	*line;
{
	while(*line) {
	  send(*line);
	  line++;
	}
}

unsigned char receive()
{
	 while (!RCIF) ;
	return(RCREG);
}

main() {
	unsigned char	i;
	unsigned char	key0,key1;

	setup_port();
	RB0 = 0;
	RB3 = 1;

	for (i=0; i<256 ;i++);

	i	= RCREG;
	i	= RCREG;
	i	= RCREG;
	sends("16F628 alive\n");

	while(1) {
	  if (!xmsec) {		//50ms毎にチェック
	    xmsec = -10;

// key check
	    key1 = switch_read();
	    if (key0 == key1) key = key0;
	    key0 = key1;

	    RB0 = RB0?0:1;
	    RB3 = RB3?0:1;
	  }
	}

}