STC单片机4x6矩阵按键程序
时间: 2023-08-18 17:28:44 浏览: 110
以下是一个基于STC单片机的4x6矩阵按键程序的示例:
```c
#include <reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit ROW1 = P1^0;
sbit ROW2 = P1^1;
sbit ROW3 = P1^2;
sbit ROW4 = P1^3;
sbit COL1 = P1^4;
sbit COL2 = P1^5;
sbit COL3 = P1^6;
sbit COL4 = P1^7;
sbit COL5 = P3^0;
sbit COL6 = P3^1;
uchar key_code[4][6]={
0x31,0x32,0x33,0x34,0x35,0x36,
0x41,0x42,0x43,0x44,0x45,0x46,
0x51,0x52,0x53,0x54,0x55,0x56,
0x61,0x62,0x63,0x64,0x65,0x66
};
uchar key_scan(void)
{
uchar i,j;
uchar code = 0xff;
ROW1 = 0;
if(COL1 == 0) {code = 0; i = 0; j = 0;}
if(COL2 == 0) {code = 1; i = 0; j = 1;}
if(COL3 == 0) {code = 2; i = 0; j = 2;}
if(COL4 == 0) {code = 3; i = 0; j = 3;}
if(COL5 == 0) {code = 4; i = 0; j = 4;}
if(COL6 == 0) {code = 5; i = 0; j = 5;}
ROW1 = 1;
ROW2 = 0;
if(COL1 == 0) {code = 6; i = 1; j = 0;}
if(COL2 == 0) {code = 7; i = 1; j = 1;}
if(COL3 == 0) {code = 8; i = 1; j = 2;}
if(COL4 == 0) {code = 9; i = 1; j = 3;}
if(COL5 == 0) {code = 10; i = 1; j = 4;}
if(COL6 == 0) {code = 11; i = 1; j = 5;}
ROW2 = 1;
ROW3 = 0;
if(COL1 == 0) {code = 12; i = 2; j = 0;}
if(COL2 == 0) {code = 13; i = 2; j = 1;}
if(COL3 == 0) {code = 14; i = 2; j = 2;}
if(COL4 == 0) {code = 15; i = 2; j = 3;}
if(COL5 == 0) {code = 16; i = 2; j = 4;}
if(COL6 == 0) {code = 17; i = 2; j = 5;}
ROW3 = 1;
ROW4 = 0;
if(COL1 == 0) {code = 18; i = 3; j = 0;}
if(COL2 == 0) {code = 19; i = 3; j = 1;}
if(COL3 == 0) {code = 20; i = 3; j = 2;}
if(COL4 == 0) {code = 21; i = 3; j = 3;}
if(COL5 == 0) {code = 22; i = 3; j = 4;}
if(COL6 == 0) {code = 23; i = 3; j = 5;}
ROW4 = 1;
if(code != 0xff) {
while(COL1 == 0 || COL2 == 0 || COL3 == 0 || COL4 == 0 || COL5 == 0 || COL6 == 0);
return key_code[i][j];
}
else {
return 0xff;
}
}
void main()
{
uchar key;
while(1)
{
key = key_scan();
if(key != 0xff) {
// 处理按下按键的操作
}
}
}
```
这个程序的基本思路是:通过轮询检测矩阵按键的状态,然后根据按键的行列位置来确定按下的键值。在程序中,我们定义了一个 4x6 的键值表 `key_code`,用于存储每个按键对应的键值。在 `key_scan` 函数中,通过轮询检测每一行的状态,然后根据列的状态来确定按下的键值。最后在主函数中,根据返回的键值来执行相应的操作。
阅读全文