矩阵键盘电路原理图
CT107D单片机中,首先将J5的跳帽接到1-2引脚,其中IAP15F2K61S2单片机中,电路变化:P37-->P44 P36-->P42
硬件实现原理
键盘扫描原理:按键左端I/O口可接高电平或者低电平(取决于板子的原理图),右端接个上拉电阻,作用是是I/O口稳定输出高电平。
要识别出黄色按键下的按键状态:逐行扫描,然后读取列的转态信号,按下按键则为低电平,没有按下则为高电平。扫描步骤如下
1、R1输出低电平,R2,R3,R4输出高电平,若C1=C2=C3=C4输出是高电平则R1行没有按键按下;
2、R2输出低电平,R1,R3,R4输出高电平,此时C1=C2=C4输出高电平,C3输出低电平,则R2C3处有按键按下;
3、R3输出低电平,R1,R2,R4输出高电平,若C1=C2=C3=C4输出是高电平则R1行没有按键按下;
4、R4输出低电平,R1,R2,R3输出高电平,若C1=C2=C3=C4输出是高电平则R1行没有按键按下;
代码实现
1 #include "reg52.h"
2
3 sfr P4 = 0xC0;
4
5 sbit R1 = P3^0;
6 sbit R2 = P3^1;
7 sbit R3 = P3^2;
8 sbit R4 = P3^4;
9
10 sbit C1 = P4^4;
11 sbit C2 = P4^2;
12 sbit C3 = P3^4;
13 sbit C4 = P3^5;
14
15 unsigned char key_num = 0;
16 unsigned char code tab[] =
17 {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
18
19 void delay(unsigned int i)
20 {
21 while(i--);
22 }
23
24 void Select(unsigned char channel)
25 {
26 switch(channel)
27 {
28 case 4:
29 P2 = P2 & 0x1f | 0x80;
30 break;
31
32 case 5:
33 P2 = P2 & 0x1f | 0xa0;
34 break;
35
36 case 6:
37 P2 = P2 & 0x1f | 0xc0;
38 break;
39
40 case 7:
41 P2 = P2 & 0x1f | 0xe0;
42 break;
43 }
44 }
45
46 void DisplayKeynum(unsigned char value)
47 {
48 Select(6);
49 P0 = 0x01;
50 Select(7);
51 P0 = value;
52 }
53
54 void scankey()
55 {
56 R1 = 0;
57 R2 = R3 = R4 = 1;
58 C1 = C2 = C3 = C4 = 1;
59
60 if(C1 == 0)
61 {
62 delay(1000);
63 if(C1 == 0)
64 {
65 while(C1 == 0);
66 key_num = 0;
67 DisplayKeynum(tab[key_num]);
68 }
69 }
70
71 else if (C2 == 0)
72 {
73 delay(1000);
74 if(C2 == 0)
75 {
76 while(C2 == 0);
77 key_num = 1;
78 DisplayKeynum(tab[key_num]);
79 }
80 }
81
82 else if (C3 == 0)
83 {
84 delay(1000);
85 if(C3 == 0)
86 {
87 while(C3 == 0);
88 key_num = 3;
89 DisplayKeynum(tab[key_num]);
90 }
91 }
92
93 else if (C4 == 0)
94 {
95 delay(1000);
96 if(C4 == 0)
97 {
98 while(C4 == 0);
99 key_num = 4;
100 DisplayKeynum(tab[key_num]);
101 }
102 }
103 }
104
105 void main()
106 {
107 while(1)
108 {
109 scankey();
110 }
111 }