/*
	FANCY1.C

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

	This program interprets the twelve keys in the upper right corner of
	the keypad as a numeric keypad. (e.g. the upper right key is interpreted
	as a '9'.)
	
	Apply a voltage to the digital inputs and a voltmeter to the digital
	outputs, then press keys 0 through 7 to toggle the state of the output
	numbered 0 through 7.
*/

#use eziopk24.lib
#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
	eioBrdInit(0);
	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-7 to toggle output");
	glPrintf(0,16,&fi6x8,"input states 0-8");
	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
			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 19: outPin = 0; break;
					case 10: outPin = 1; break;
					case 18: outPin = 2; break;
					case 26: outPin = 3; break;
					case 9: outPin = 4; break;
					case 17: outPin = 5; break;
					case 25: outPin = 6; break;
					case 8: outPin = 7; break;
					default: outPin = -1; break;
				}
				outputState ^= 1 << outPin;
				if (outPin >= 0) {
					kdiBuzSw(1);
					kdiELSw(1);
					glPrintf(0,8,&fi6x8,"Output %02d toggled", outPin);
					if (outputState & (1 << outPin)) {
						eioBrdDO(outPin, 1);
					} else {
						eioBrdDO(outPin, 0);
					}
					kdiBuzSw(0);
					kdiELSw(0);
				}
			}
		}
		for (i = 0; i < 9; ++i) {
			glPrintf(i*6,24,&fi6x8,eioBrdDI(i)?"1":"0");
		}
	}
}