#define KeyEn porta.6
#define KeyEnTris trisa.6
#define KeyTris trisb
#define KeyDelay 30
#define KeyRepeat 10
#define key_none 0
#define key_back 1
#define key_up 2
#define key_dw 3
#define key_enter 4
unsigned char keys=0,previous,edges,KeyCount;
char ReadKeyPad(){
char i;
previous=keys; //keep copy of previous state
option_reg.7=0; //WPUs on
KeyTris|=0x3c; //B2-B6 input
KeyEnTris=0; //A6 output
KeyEn=0; //and low
[color=red]delay_us(10);[/color] //see text below
keys=(portb>>2)&0x0f; //read keys
keys^=0x0f; //invert them so 1=pressed
KeyEnTris=1; //switch en back to input
KeyTris&=0xc3; //switch b2-b6 back to output
if(keys==0) //if no key pressed
return(0); //return zero
//now do key repeat and delay stuff
//keys xor previous gives us a 1 if a key has changed
//ANDing this value with the new keys pressed gives
//keys that were 0 last time and 1 now = new presses
if(((keys^previous)&keys)==0){ //if no new presses
//must be repeating key
if(--KeyCount!=0) //decrement key count and
return(0); //return zero as time not up
KeyCount=KeyRepeat; //reset key timer
}else{
//must be new key press
KeyCount=KeyDelay; //set initial delay
edges=((keys^previous)&keys);//see above
}
i=0;
while((edges&(1<<i))==0){ //change bit pattern into 1 to 3
i++;
}
return (++i); //and return it
}