matrix keypad 3


Using 4x4 matrix keypad with MINI-MAX/AVR-C

Toolkit:AVR Development System

Location:/bipom/devtools/WinAVR/minimaxavrc/Examples/Labs/Lab07

Code Example


#define MAX_ROWS	4
#define MAX_COLS	4

static char KeyTable[] = { 	'1', '2', '3', 'A',
							'4', '5', '6', 'B',	 
							'7', '8', '9', 'C',
							'*', '0', '#', 'D'		};

// *********************************************************************

int main(void)
{
	char key;

	/* Initialize the UART1 */
	uart0Init(19200);	
		
	uart0Printf("Waiting for key\n");
	
	while(1)
	{
		key = ScanKeypad();

		if( key )
			uart0Printf( "\n\rKey: '%c'", key );
	}		
}



/*********************************************************************
*                                                                   
*      Function :  ScanKeypad - Scanning keypad for pressed key
*
*      Inputs:    none
*
*      Returns -  char  - if  pressed key - the key code 
*                         else zero
*                                                                                       
*********************************************************************/

char ScanKeypad()
{
	char row = 0;
	char col = 0;
	
	col = 0;  //  current column 

	
	// Check first row

	ClrIO(TEST_PORT_K,ROW_1);
	SetIO(TEST_PORT_K,ROW_2);
	SetIO(TEST_PORT_K,ROW_3);
	SetIO(TEST_PORT_K,ROW_4);
		
	if( !(GetInput(TEST_PORT_H,COL_1)) )col = 1;
	if( !(GetInput(TEST_PORT_H,COL_2)) )col = 2;
	if( !(GetInput(TEST_PORT_H,COL_3)) )col = 3;
	if( !(GetInput(TEST_PORT_H,COL_4)) )col = 4;

	if( col != 0 )		
		{
			_delay_ms(500);
			return KeyTable[col-1 + row*MAX_COLS];
		}
	row++;

	// Check second row

	SetIO(TEST_PORT_K,ROW_1);
	ClrIO(TEST_PORT_K,ROW_2);
	SetIO(TEST_PORT_K,ROW_3);
	SetIO(TEST_PORT_K,ROW_4);
		
	if( !(GetInput(TEST_PORT_H,COL_1)) )col = 1;
	if( !(GetInput(TEST_PORT_H,COL_2)) )col = 2;
	if( !(GetInput(TEST_PORT_H,COL_3)) )col = 3;
	if( !(GetInput(TEST_PORT_H,COL_4)) )col = 4;

	if( col != 0 )		
		{
			_delay_ms(500);
			return KeyTable[col-1 + row*MAX_COLS];
		}
	row++;
			
	// Check third row

	SetIO(TEST_PORT_K,ROW_1);
	SetIO(TEST_PORT_K,ROW_2);
	ClrIO(TEST_PORT_K,ROW_3);
	SetIO(TEST_PORT_K,ROW_4);
		
	if( !(GetInput(TEST_PORT_H,COL_1)) )col = 1;
	if( !(GetInput(TEST_PORT_H,COL_2)) )col = 2;
	if( !(GetInput(TEST_PORT_H,COL_3)) )col = 3;
	if( !(GetInput(TEST_PORT_H,COL_4)) )col = 4;

	if( col != 0 )		
		{
			_delay_ms(500);
			return KeyTable[col-1 + row*MAX_COLS];
		}
	row++;
								
	// Check fourth row

	SetIO(TEST_PORT_K,ROW_1);
	SetIO(TEST_PORT_K,ROW_2);
	SetIO(TEST_PORT_K,ROW_3);
	ClrIO(TEST_PORT_K,ROW_4);
		
	if( !(GetInput(TEST_PORT_H,COL_1)) )col = 1;
	if( !(GetInput(TEST_PORT_H,COL_2)) )col = 2;
	if( !(GetInput(TEST_PORT_H,COL_3)) )col = 3;
	if( !(GetInput(TEST_PORT_H,COL_4)) )col = 4;

	if( col != 0 )		
		{
			_delay_ms(500);
			return KeyTable[col-1 + row*MAX_COLS];
		}
	row++;	
	return 0;
}