Body of the function
UnsignedCharGetKey () {unsignedChari,j,k; StaticUnsignedCharbackup[4][4]={ {1,1,1,1},{1,1,1,1},{1,1,1,1},{1,1,1,1} }; EA=1; Tmod=0x01;//set T0 to mode 1th0=0xF8; TL0=0xCD; ET0=1;//Enable T0 interrupttr0=1;//Start T0 while(1) { for(i=0;i<4; i++)//cyclic detection of 4x4 matrix keys { for(j=0;j<4; j + +) { if(Backup[i][j]!=keysta[i][j])//Detecting Key Actions { if(backup[i][j]!=0)//To perform an action when the key is pressed{k=i*4+J; returnK//returns the number of the matrix key} Backup[i][j]=KEYSTA[I][J];//Update the previous backup value } } } }}
The following is the interrupt function
/*T0 Interrupt service function, scan matrix key state and Shake*/voidINTERRUPTTIMER0 () Interrupt1{unsignedCharm; StaticUnsignedCharkeyout=0;//matrix key Scan Output Index StaticUnsignedCharkeybuf[4][4]={ {0xFF,0xFF,0xFF,0xFF},{0xFF,0xFF,0xFF,0xFF}, {0xFF,0xFF,0xFF,0xFF},{0xFF,0xFF,0xFF,0xFF} }; TH0=0xFC; TL0=0x67; /*move 4 key values in a row into a buffer*/keybuf[keyout][0]= (keybuf[keyout][0]<<1)|key_in_1; keybuf[keyout][1]= (keybuf[keyout][1]<<1)|key_in_2; keybuf[keyout][2]= (keybuf[keyout][2]<<1)|Key_in_3; keybuf[keyout][3]= (keybuf[keyout][3]<<1)|Key_in_4; /*Update button state after Shake*/ for(m=0;m<4; m++) { if((keybuf[keyout][m]&0x0F)==0x00) {Keysta[keyout][m]=0;//4 consecutive scan value is 0, that is, the 4x4ms is pressed in the state, you can think that the button has been stably pressed } Else if((keybuf[keyout][m]&0x0F)==0x0F) {Keysta[keyout][m]=1;//pop Up } /*perform the next scan output*/Keyout++;//Output Index Incrementkeyout=keyout&0x03;//index value increased to 4 is zero /*releases the current output pin according to the index, pulling down the next input pin*/ Switch(keyout) { Case 0: key_out_4=1; key_out_1=0; Break; Case 1: key_out_1=1; Key_out_2=0; Break; Case 2: key_out_2=1; key_out_3=0; Break; Case 3: key_out_3=1; key_out_4=0; Break; default: Break; } }}
This code completes the scanning, chattering, and motion separation of the matrix keyboard, and it is convenient to call Getkey () to return the number of the pressed button.
Matrix keyboard Scanning algorithm