蓝桥杯单片机必备知识-----矩阵按键
Posted 南岸青栀*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了蓝桥杯单片机必备知识-----矩阵按键相关的知识,希望对你有一定的参考价值。
蓝桥杯单片机必备知识-----(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;
以上是关于蓝桥杯单片机必备知识-----矩阵按键的主要内容,如果未能解决你的问题,请参考以下文章