/*
	FANCY1.C

	Example of keypad input, digital input reading and digital output
	manipulation.

	Apply a voltage to the digital inputs and a voltmeter to the digital
	outputs, then follow the directions on the PK2240 lcd.
*/

#use vdriver.lib
#use kdi.lib
#use kp.lib
#use wintek.lib
#use glcd.lib

struct _fontInfo fi6x8;

main() {
	auto unsigned long msMark;
	auto unsigned i;
	auto int exitNow;
	auto int inputKey;
	auto int outputState;
	auto int keyPressed;
	auto int outPin;
	
	VdInit();		//	kernel initialization
	glInit();		//	graphics LCD initialization
	kpDefInit();	//	initialize keypad module
	glXFontInit(&fi6x8, 6, 8, 32, 127, engFont6x8);	//	initialize basic font
	glSetBrushType(GL_BLOCK);
	outputState = 0;
	glPrintf(0,0,&fi6x8,"0-9 to toggle output");
	glPrintf(0,16,&fi6x8,"input states 1-16");
	while (1) {
		kpScanState();	//	scan the state of the keypad, no interpretation
		keyPressed = kpDefGetKey();	//	interpret the state just scanned
												//	and put the code into keyPressed
		if (keyPressed == -1) {			//	-1 means no key activity is detected
		} else {								//	otherwise, some activity took place
			outport(BUZZER,0xff);		//	start beeper
			kdiELSw(1);
			if (keyPressed & 0x100) {	//	falling edge (key released)
				//	decode the row and column
			} else {							//	rising edge (key pressed)
				//	decode the row and column
				switch (keyPressed) {
					case 1: outPin = 0; break;
					case 8: outPin = 1; break;
					case 9: outPin = 2; break;
					case 10: outPin = 3; break;
					case 16: outPin = 4; break;
					case 17: outPin = 5; break;
					case 18: outPin = 6; break;
					case 24: outPin = 7; break;
					case 25: outPin = 8; break;
					case 26: outPin = 9; break;
					default: outPin = -1; break;
				}
				glPrintf(0,8,&fi6x8,"Output %02d toggled", outPin+1);
				outputState ^= 1 << outPin;
				if (outputState & (1 << outPin)) {
					up_setout(outPin+1, 1);
				} else {
					up_setout(outPin+1, 0);
				}
			}
			outport(BUZZER,0);			//	stop beeper
			kdiELSw(0);
		}
		for (i = 1; i < 17; ++i) {
			glPrintf(i*6-6,24,&fi6x8,up_digin(i)?"1":"0");
		}
	}
}