蓝桥杯单片机必备知识—–(6)矩阵按键
思路: 就是线反转法
线反转法:将控制行的线置高控制列的线置地,如果哪个低,则为哪一行有按键按下;然后将控制列的线置高控制行的线置地,如果哪个低,则为哪一列有按键按下。如此之后就可以确定到底是哪个按键按下。
注:跳线帽设置为KBD!!!!!
扫描键盘函数
void read_key()
{
static unsigned char hang;
static unsigned char state = 0;
switch(state)
{
case 0:
{
P3 = 0x0f;P42 = 0;P44 = 0;
if(P3 != 0x0f) state = 1;
}break;
case 1:
{
P3 = 0x0f; P42 = 0; P44 = 0; //列置低,行置高
if(P3 != 0x0f) //判断行
{
if(P33 == 0) hang = 1;
if(P32 == 0) hang = 2;
if(P31 == 0) hang = 3;
if(P30 == 0) hang = 4;
switch(hang)
{
case 1:
{
P3 = 0xf0;P42 = 1;P44 = 1; //行置低,列置高
if(P44 == 0){
s4++;state = 2;hang = 0;}
if(P42 == 0){
s8++;state = 2;hang = 0;}
if(P35 == 0){
s12++;state = 2;hang = 0;}
if(P34 == 0){
s16++;state = 2;hang = 0;}
}break;
case 2:
{
P3 = 0xf0;P42 = 1;P44 = 1;
if(P44 == 0){
s5++;state = 2;hang = 0;}
if(P42 == 0){
s9++;state = 2;hang = 0;}
if(P35 == 0){
s13++;state = 2;hang = 0;}
if(P34 == 0){
s17++;state = 2;hang = 0;}
}break;
case 3:
{
P3 = 0xf0;P42 = 1;P44 = 1;
if(P44 == 0){
s6++;state = 2;hang = 0;}
if(P42 == 0){
s10++;state = 2;hang = 0;}
if(P35 == 0){
s14++;state = 2;hang = 0;}
if(P34 == 0){
s18++;state = 2;hang = 0;}
}break;
case 4:
{
P3 = 0xf0;P42 = 1;P44 = 1;
if(P44 == 0){
s7++;state = 2;hang = 0;}
if(P42 == 0){
s11++;state = 2;hang = 0;}
if(P35 == 0){
s15++;state = 2;hang = 0;}
if(P34 == 0){
s19++;state = 2;hang = 0;}
}break;
}
}
else state = 0;
}break;
case 2: //判断按键是否松开
{
P3 = 0x0f;P42 = 0;P44 = 0;
if(P3 == 0x0f) state = 0;
}break;
}
}
测试效果图:
一般蓝桥杯会使用s4s5s8s9小矩形键盘来测试你对矩阵键盘的掌握程度。
小矩阵键盘
void read_key()
{
static unsigned char hang;
static unsigned char state = 0;
switch(state)
{
case 0:
{
P3 = 0x0f;P42 = 0;P44 = 0;
if(P3 != 0x0f) state = 1;
}break;
case 1:
{
P3 = 0x0f; P42 = 0; P44 = 0;
if(P3 != 0x0f)
{
if(P33 == 0) hang = 1;
if(P32 == 0) hang = 2;
switch(hang)
{
case 1:
{
P3 = 0xf0;P42 = 1;P44 = 1;
if(P44 == 0){
s4++;state = 2;hang = 0;}
if(P42 == 0){
s8++;state = 2;hang = 0;}
}break;
case 2:
{
P3 = 0xf0;P42 = 1;P44 = 1;
if(P44 == 0){
s5++;state = 2;hang = 0;}
if(P42 == 0){
s9++;state = 2;hang = 0;}
}break;
}
}
else state = 0;
}break;
case 2:
{
P3 = 0x0f;P42 = 0;P44 = 0;
if(P3 == 0x0f) state = 0;
}break;
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/100142.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...