matrix keypad 1


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

Toolkit:AVR Development System

Location:/bipom/devtools/WinAVR/minimaxavrc/Examples/keypad4x4

Code Example


#define MAX_ROWS	4
#define MAX_COLS	4

static char KeyTable[] = { 	'1', '2', '3', 'D',
							'4', '5', '6', 'A',	 
							'7', '8', '9', 'B',
							'*', '0', '#', 'D'
						 };
						
static unsigned char RowTable[] = { 0xFE, 0xFD, 0xFB, 0xF7 };

char ScanKeypad();

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

int main (void)
{
    char key;

	// delay 500 milliseconds after power up

	_delay_ms(500);        

	// Initialize the serial port 0 to 19200 baud

	uart0Init(19200);

	// Initialize the serial port 1 to 19200 baud

	uart1Init(19200);
	
	
	
	// Set lower 4 bits of Port K as output, these are the rows of the keypad

	DDRK |= _BV(PK0);
	DDRK |= _BV(PK1);
	DDRK |= _BV(PK2);
	DDRK |= _BV(PK3);

	// Set upper 4 bits of Port H as input, these are the columns of the keypad

	
	PORTH |= _BV(PH4);     // Enable internal pull-up resistor for PH4 so it will not float

	PORTH |= _BV(PH5);     // Enable internal pull-up resistor for PH5 so it will not float

	PORTH |= _BV(PH6);     // Enable internal pull-up resistor for PH6 so it will not float

	PORTH |= _BV(PH7);     // Enable internal pull-up resistor for PH7 so it will not float

	
	DDRH &= ~_BV(PH4);     // Set PH4 as input

	DDRH &= ~_BV(PH5);     // Set PH5 as input

	DDRH &= ~_BV(PH6);     // Set PH6 as input

	DDRH &= ~_BV(PH7);     // Set PH7 as input



	uart0Printf("\n\rWaiting for key press\n\r");
	uart1Printf("\n\rWaiting for key press\n\r");
	
	// Loop forever

	for( ;; )
	{
	    // Check to see if a key was pressed

		key = ScanKeypad();

        // If a key was pressed

		if( key )
		{
			// Print the key to both serial ports

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


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

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

	
	// Scan the keypad

	for( row=0; row<MAX_ROWS; row++ )
	{
		PORTK = RowTable[row];

		if( !(PINH & 0x80) ) col = 4;
		if( !(PINH & 0x40) ) col = 3;
		if( !(PINH & 0x20) ) col = 2;
		if( !(PINH & 0x10) ) col = 1;
			
		// Is any key pressed ?

		if( col != 0 )		
		{
		      // key debounce delay

			_delay_ms(500);

            // return the key that was pressed			

			return KeyTable[col-1 + row*MAX_COLS];
		}					
	}
	
	return 0;
}