# 兩種狀態機掃描按鍵，第二種只要三行！！！ -开发者知识库

``` 1 sbit r1=P3^0;
2 sbit r2=P3^1;
3 sbit r3=P3^2;
4 sbit r4=P3^3;
5 sbit c1=P4^4;
6 sbit c2=P4^2;
7 sbit c3=P3^5;
8 sbit c4=P3^4;
9
10 unsigned char matrix_scan()
11 {
12     static unsigned char state=0x00;
13     unsigned char keyval=16;
14
15     switch (state)
16     {
17         case 0x00:
18             r1=r2=r3=r4=0;
19             c1=c2=c3=c4=1;
20             if (!(c1&c2&c3&c4))
21                 state=0x01;
22             break;
23         case 0x01:
24             r1=r2=r3=r4=0;
25             c1=c2=c3=c4=1;
26             if (!(c1&c2&c3&c4))
27             {
28                 r1=0;
29                 r2=r3=r4=c1=c2=c3=c4=1;
30                 if (!c1) keyval=0;
31                 else if (!c2) keyval=1;
32                 else if (!c3) keyval=2;
33                 else if (!c4) keyval=3;
34
35                 r2=0;
36                 r1=r3=r4=c1=c2=c3=c4=1;
37                 if (!c1) keyval=4;
38                 else if (!c2) keyval=5;
39                 else if (!c3) keyval=6;
40                 else if (!c4) keyval=7;
41
42                 r3=0;
43                 r2=r1=r4=c1=c2=c3=c4=1;
44                 if (!c1) keyval=8;
45                 else if (!c2) keyval=9;
46                 else if (!c3) keyval=10;
47                 else if (!c4) keyval=11;
48
49                 r4=0;
50                 r2=r3=r1=c1=c2=c3=c4=1;
51                 if (!c1) keyval=12;
52                 else if (!c2) keyval=13;
53                 else if (!c3) keyval=14;
54                 else if (!c4) keyval=15;
55
56                 state=0x02;
57                 r1=r2=r3=r4=0;
58                 c1=c2=c3=c4=1;
59             }
60             break;
61         case 0x02:
62             if (c1&c2&c3&c4)
63                 state=0x00;
64             break;
65     }
66     return keyval;
67 }```

DABAN RP主题是一个优秀的主题，极致后台体验，无插件，集成会员系统
U19学习网站 » 兩種狀態機掃描按鍵，第二種只要三行！！！ -开发者知识库