#include <avr/io.h> // Include file for AVR
#include <util/delay.h>
#include "lcd.h"
#define keyport PORTA //Keypad Port
#define keyportddr DDRA //Data Direction Register
#define keyportpin PINA //Keypad Port Pins
#define col1 PA0 //Column1 PortA.0
#define col2 PA1 //Column2 PortA.1
#define col3 PA2 //Column3 PortA.2
#define col4 PA3 //Column4 PortA.3
#define TRUE 1
#define FALSE 0
unsigned char keyval; //A variable
void key_init(){
keyportddr = 0xF0;
keyport = 0x0F;
}
unsigned char get_key(){
unsigned char i,key=1;
for(i=0;i<4;i++){ //Loop for 4 rows
keyport &=~(0x80>>i); //Make rows low one by one
if(!(keyportpin & (1<<col1))){
//check COL1
while(!(keyportpin & (1<<col1)));
//wait for release
return key;
//return pressed key value
}
if(!(keyportpin & (1<<col2))){
//Check COL2
key += 1;
//Second key pressed
while(!(keyportpin & (1<<col2)));
//wait for release
return key;
//return key value
}
if(!(keyportpin & (1<<col3))){
//Check COL3
key += 2;
//Third key pressed
while(!(keyportpin & (1<<col3)));
//Wait for release
return key;
//Return value
}
if(!(keyportpin & (1<<col4))){
//check COL4
key += 3;
//Fourth key pressed
while(!(keyportpin & (1<<col4)));
//Wait for release
return key;
//Return key value
}
key +=4; //Next row
keyport |= 0x80>>i;
//make read row high again
}
return FALSE; //return false if no key pressed
}
int main(void){
MCUCSR=0x80;
MCUCSR=0x80;
//Initialize LCD module
InitLCD(LS_BLINK|LS_ULINE);
//Clear the screen
LCDClear();
//Simple string printing
LCDWriteString("Type the Number ");
unsigned char keyval;
key_init();
while(1){
keyval = get_key();
if(keyval != 0){
LCDClear();
LCDWriteString("You have entered");
LCDWriteIntXY(1,1,keyval,3);
}
}
}