波特律动
课程中心/51单片机教程/【11】矩阵键盘

【11】矩阵键盘

【02】点灯大师

写下第一段 51 单片机代码,编译 HEX 文件并下载到学习板,点亮 L0 。



本课资源下载
3 个资源
P02小灯闪烁

本节课的标准源代码工程/可供参考

V1.0压缩包23 KB
下载
XL-1608SURC-06

LED红色(0603)

PDF 文档1.5 MB
预览下载
流水灯原理图

交互式原理图❇️

原理图

课程笔记


本节目标概括

创建main.c > 编写点灯代码 > 编译HEX文件 > 下载到学习板 > 点亮第一颗LED小灯

编译并下载程序到学习板,即可看到程序效果:

  • 按下哪一个按键,LCD屏幕显示对应的按键数字

例程讲解

矩阵按键的逻辑函数:

C语言
1unsigned char key_read(void)
2{
3 unsigned char key_state = 0;
4
5 P20 = 0; P21 = 1; P22 = 1; P23 = 1;
6 if(P24 == 0) key_state = 11;
7 if(P25 == 0) key_state = 12;
8 if(P26 == 0) key_state = 13;
9 if(P27 == 0) key_state = 14;
10
11 P20 = 1; P21 = 0; P22 = 1; P23 = 1;
12 if(P24 == 0) key_state = 21;
13 if(P25 == 0) key_state = 22;
14 if(P26 == 0) key_state = 23;
15 if(P27 == 0) key_state = 24;
16
17 P20 = 1; P21 = 1; P22 = 0; P23 = 1;
18 if(P24 == 0) key_state = 31;
19 if(P25 == 0) key_state = 32;
20 if(P26 == 0) key_state = 33;
21 if(P27 == 0) key_state = 34;
22
23 P20 = 1; P21 = 1; P22 = 1; P23 = 0;
24 if(P24 == 0) key_state = 41;
25 if(P25 == 0) key_state = 42;
26 if(P26 == 0) key_state = 43;
27 if(P27 == 0) key_state = 44;
28
29 P20 = 1; P21 = 1; P22 = 1; P23 = 1;
30
31 return key_state;
32}

P20 = 0; P21 = 1; P22 = 1; P23 = 1;P20赋值为0,打开一侧的矩阵开关

if(P24 == 0) key_state = 11;再次检测P24是否为0,若为0,则可以通过两次定位确定按键为11,所以返回值为11

主函数:

C语言
1#include <STC89C5xRC.H>
2#include <key.h>
3#include <LCD1602.h>
4
5
6void main()
7{
8 unsigned char key;
9 P43=0;
10 LCD_Init();
11 while(1)
12 {
13 key=key_read();
14 LCD_ShowNum(1,1,key,2);
15 }
16
17}