/*
	MGLCDKEY.C
	
	BL14xx/MicroG or BL15xx/MicroG2
	
	Use 8 bit of PIOA and 4 bits of PIOB to drive the LCD in and scan
	a 4x6 or 2x6 keypad. The following wiring is used:

      PIO      LCD         KEYPAD
     -----  ---------   ------------

		PA0						KEYREAD1
		PA1						KEYREAD2
		PA2		RS
		PA3		EN
		PA4		DB4			DRVR1
		PA5		DB5			DRVR2
		PA6		DB6			DRVR3
		PA7		DB7			DRVR4

		PB4						KEYREAD3
		PB5						KEYREAD4
		PB6						KEYREAD5
		PB7						KEYREAD6
		
		Vcc		Vcc
		Gnd		Vss
		Gnd		Vo				(for better contrast, tie Vo to 0.3 volt)
		Gnd		R/W

	Scanning the keypad is done when the function lc_keyscan() is called.
	A valid key has to be pressed for consecutive DebounceCount times
	lc_keyscan() is called. For example, if DebounceCount is 10 and
	lc_keyscan() is called by a PRT1 every 25ms, then 10*25ms = 250 ms is
	the minimum amount of time a key has to be pressed to register as a valid
	key. 

	You may optionally use the MicroG-to-PLCBus/LCD adapter. If so, be sure to
	uncomment the line including the "#define ESSTART_NOTINPUT" statement.
*/

//#define ESSTART_NOTINPUT

#define KEY4x6			// if 4x6 keypad
#define DebounceCount 10

main()
{
	int i, j, k;
	int key, oldkey;
	unsigned int count;

	count = 0;	
	lc_kxinit();		// initialize the keypad first
	lc_init();			// initialize the LCD
	
	set_timer1(25);	// set timer1 to interrupt every 25ms
							// timer1 interrupt routine calls lc_keyscan() to
							// scan the keypad.

	lc_printf("hello world,cnt  key");	
	for(;;)
	{
		hitwd();
		runwatch();

		if((key = lc_kxget(0))!= -1)
		{
			if(oldkey!=key)
			{
				oldkey = key;
				count = 0;
			}
			count++;
			lc_printf("\x1bp100keypressed  %2d >> %2d", count, key);
		}
	}
}
	
// set_timer1(unsigned int milliseconds)
// Load and start timer1 to interrupt periodically for the specified 
// milliseconds.
int set_timer1(unsigned int milliseconds)
{
	unsigned int load_value;

	if(milliseconds >= 200) milliseconds = 200;     
																// limit to 200 millisecond
	load_value = (float) milliseconds*307.2;

	DI();
	// timer1 interrupt every (load_value*20)/6144000 

	outport(TCR, inport(TCR) & '\B11011101');    // inhibit TIMER1 interrupt
	outport(TMDR1L, load_value & 0xff);
	outport(TMDR1H, (load_value >> 8) & 0xff);
	outport(RLDR1L, load_value & 0xff);
	outport(RLDR1H, (load_value >> 8) & 0xff);

	outport(TCR, inport(TCR) | '\B00100010');
	EI();
}


#INT_VEC PRT1_VEC timer1

interrupt timer1()
{
		inport(TCR);            // reset the interrupt
		inport(TMDR1L);         // reset the interrupt
		lc_keyscan();				// key scanner, call periodically
}




