📄 matrix_key.c
字号:
#include "Matrix_Key.h"
/*
* 矩阵键盘通用程序(引脚输入输出方向不切换)
*/
//KEY_PINS 低4位为ROW(监听) 高4位为COL(输出,低电平)
// 7 6 5 4 3 2 1 0
// Co4 Co3 Co2 Co1 Ro4 Ro3 Ro2 Ro1
/* COL 4 3 2 1
ROW 4
3
2
1
*/
unsigned char row=0,col=0;
//<返回其列号(col) 需要事先准备其行号掩码>
static unsigned char Matrix_Key_Scan_Col(const unsigned char rowbitmask)
{
unsigned char i=0;
unsigned char colmask;
KEY_PINS = 0x0f;
colmask=0x0f;
while ( (KEY_PINS & rowbitmask)==0)
{
colmask = colmask<<1;
KEY_PINS = colmask | 0x0f;
i++;
}
return i;
}
//<检测是否有按键按下,并返回其行号(row)>
static unsigned char Matrix_Key_Scan_Row()
{
KEY_PINS = 0x0f;
if (ROW1 == 0)
{
return 1;
}
else if (ROW2 == 0)
{
return 2;
}
else if (ROW3 == 0)
{
return 3;
}
else if (ROW4 == 0)
{
return 4;
}
return 0;
}
unsigned char Matrix_Key_Detect() //行/列
{
static unsigned char keep_time;
static unsigned char keep_row;
static unsigned char keep_col;
static unsigned char state = 0;
unsigned char uScanReturn;
switch (state)
{
case 0: //检测是否有按钮按下
if (Matrix_Key_Scan_Row() != 0 )
{ //<初始化>
keep_time = 0;
keep_row = 0;
keep_col = 0;
state++;
}
break;
case 1:
uScanReturn = Matrix_Key_Scan_Row();
if (uScanReturn != 0 ) //按键按下姿态
{
if (keep_time<250) keep_time++;
if (keep_row == 0)
{
keep_row = uScanReturn;
}
if (keep_row != 0 && keep_col == 0)
{
keep_col = Matrix_Key_Scan_Col( 0x01<<(keep_row-1) );
}
}
else //按键松起姿态
{
if (keep_time>5) //检测到有效按键
{
keep_time = 0;
state++;
}
else //按键无效
{
state = 0;
}
}
break;
case 2:
if (Matrix_Key_Scan_Row() == 0 ) //按键松起姿态(保持)
{
if (keep_time<250) keep_time++;
if (keep_time>5) //检测到有效松起
{
/* 返回信息:检测到有效按键,并可以执行对应操作 */
state = 0;
row = keep_row;
col = keep_col;
return 1;
}
}
else //按键被重新按下
{
keep_time=0; //重新计时
}
break;
}
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -