按键盘数码管流动显示实验
扫描二维码
随时随地手机看文章
要求:按下键盘,六个数码管流动显示按下的值。
连线:将片选CS0接到key_LED_CS上
1 #include
2 #define LEDLen 6
3
4 xdata unsigned char OUTBIT _at_ 0x8002; // 位控制口
5 xdata unsigned char OUTSEG _at_ 0x8004; // 段控制口
6 xdata unsigned char IN _at_ 0x8001; // 键盘读入口
7
8 unsigned char LEDBuf[LEDLen]; // 显示缓冲
9 code unsigned char LEDMAP[] = { // 八段管显示码 (点不显示,0-F)
10 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
11 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71
12 };
13
14 code unsigned char KeyTable[] = { // 键码定义
15 0x16, 0x15, 0x14, 0xff,
16 0x13, 0x12, 0x11, 0x10,
17 0x0d, 0x0c, 0x0b, 0x0a,
18 0x0e, 0x03, 0x06, 0x09,
19 0x0f, 0x02, 0x05, 0x08,
20 0x00, 0x01, 0x04, 0x07
21 };
22
23
24 void Delay(unsigned char CNT)
25 {
26 unsigned char i;
27 while (CNT-- !=0)
28 for (i=100; i !=0; i--);
29 }
30
31 void DisplayLED()
32 {
33 unsigned char i;
34 unsigned char Pos;
35 unsigned char LED;
36
37 Pos = 0x20; // 从左边开始显示
38 for (i = 0; i < LEDLen; i++) {
39 OUTBIT = 0; // 关所有八段管
40 LED = LEDBuf[i];
41 OUTSEG = LED;
42 OUTBIT = Pos; // 显示一位八段管
43 Delay(2);
44 Pos >>= 1; // 显示下一位
45 }
46 }
47
48
49 unsigned char TestKey()
50 {
51 OUTBIT = 0; // 输出线置为0
52 return (~IN & 0x0f); // 读入键状态(高四位不用)
53 }
54
55 unsigned char GetKey()
56 {
57 unsigned char Pos;
58 unsigned char i;
59 unsigned char k;
60
61 i = 6;
62 Pos = 0x20; // 找出键所在列
63 do {
64 OUTBIT = ~ Pos;
65 Pos >>= 1;
66 k = ~IN & 0x0f;
67 } while ((--i != 0) && (k == 0));
68
69 // 键值 = 列 x 4 + 行
70 if (k != 0)
71 {
72 i *= 4;
73 if (k & 2)
74 i += 1;
75 else if (k & 4)
76 i += 2;
77 else if (k & 8)
78 i += 3;
79
80 OUTBIT = 0;
81 do
82 Delay(10); while (TestKey()); // 等键释放
83
84 return(KeyTable[i]); // 取出键码
85 } else return(0xff);
86 }
87
88 void main()
89 { unsigned int i=0;
90 LEDBuf[0] = 0x00; //如果设置为3F那么最初第一个数码管显示为0
91 LEDBuf[1] = 0x00;
92 LEDBuf[2] = 0x00;
93 LEDBuf[3] = 0x00;
94 LEDBuf[4] = 0x00;
95 LEDBuf[5] = 0x00;
96
97 while (1) {
98 DisplayLED();
99 if (TestKey())
100 {
101
102 LEDBuf[i++%6] = LEDMAP[GetKey() & 0x0f];
103 //LEDBuf[5]=LEDMP[GetKey()&0x0f];
104 }
105 }
106 }