51. 52 single-chip microcomputer matrix keyboard, 5152 single-chip microcomputer Matrix
To learn about the matrix keyboard, first make a small experiment: After you press the matrix keyboard, the digital display displays the number of keys that are pressed.
My matrix keyboard is 4x4. The operating principle is to first check which line of key is pressed. Then determine the column. In this way, you can identify which key is pressed.
First, let's look at the circuit diagram to determine which needle is used to connect the keyboard to the CPU. My Development Board is connected to P1, specifically P10 ~ P17, eight 8 bits for the logic.
(This is omitted and code is directly pasted)
# Include <reg52.h>
Void delay (int n );
Void juzhen (void );
Char duanxuan [16] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d,
0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79,0x71 };
Char keyveluetonumber [17] = {0X0 0x77, 0x7B, 0X7D, 0X7E, 0XB7, 0XBB, 0XBD, 0XBE,
0XD7, 0XDB, 0XDD, 0XDE, 0XE7, 0XEB, 0XED, 0XEE };
Int keyvelue = 0;
Int main (){
Int j = 0;
P2 = 0XFF;
While (1 ){
Juzhen ();
P0 = duanxuan [keyvelue];
}
}
Void juzhen (void ){
Int a = 0, I;
Char tempkey;
P1 = 0xf0;
If (P1! = 0Xf0 ){
Delay (10 );
If (P1! = 0Xf0 ){
Tempkey = P1;
P1 = 0X0f;
Tempkey | = P1;
For (I = 1; I <= 16; I ++) {/* switch optimization Code */
If (keyveluetonumber [I] = tempkey ){
Keyvelue = I;
Break;
}
}
/* Switch (tempkey) {// the corresponding relationship of the switch is more intuitive, but this programming is too 2,
Therefore, use arrays to map subscript and element in advance and query them directly.
It does not save time, but saves the programmer's energy.
Case 0x77: keyvelue = 1; break;
Case 0x7B: keyvelue = 2; break;
Case 0X7D: keyvelue = 3; break;
Case 0X7E: keyvelue = 4; break;
Case 0XB7: keyvelue = 5; break;
Case 0XBB: keyvelue = 6; break;
Case 0XBD: keyvelue = 7; break;
Case 0XBE: keyvelue = 8; break;
Case 0XD7: keyvelue = 9; break;
Case 0XDB: keyvelue = 10; break;
Case 0XDD: keyvelue = 11; break;
Case 0XDE: keyvelue = 12; break;
Case 0XE7: keyvelue = 13; break;
Case 0XEB: keyvelue = 14; break;
Case 0XED: keyvelue = 15; break;
Case 0XEE: keyvelue = 16; break;
}
*/
}
}
Return;
}
Void delay (int n) {// simple latency Function
Int I;
While (n --)
For (I = 110; I> 0; I --);
}