蓝桥杯的独立按键包含在矩阵按键里,由按键右侧的跳线帽接触决定。独立按键将J5的2和3用跳线帽连接起来,矩阵键盘必须将1 2 接一起,同时应注意使用STC15F2K60S2转接板时,管脚转换的过程 P42->P37, P44->P36。不然会导致前两列矩阵键盘不可用
如果用的是<reg52.h>这个头文件,要注意,52是没有P4口,因此我们要自己定义P4口
sfr P4=0xc0;
检测原理:
单片机上电之后P3的8个IO口全部都是高电平,按键一端连接的是GND,按键按下电路接通使得另外一端的电平变成了低电平,也就是说我们只要检测对应的IO口是不是低电平就可以检测按键是否按下。
从原理图可以看到,当J5的2和3连接的时候,如果S7被按下,则P30会变成低电平,同样的S6对应着P31,S5对应P32,S4对应P33。
#include <STC15F2K60S2.h>
#define uchar unsigned char
#define uint unsigned int
void allinit();
void keyscan16();
void Delay1ms(uchar z);
uchar temp;
void main()
{
allinit();
P2=0X80;//P2口必须设置为0x80(或者想要操作的数码管,蜂鸣器,继电器),否则打开的不是数码管
//也可将led最后初始化
P0=0XFF;
while(1)
{
keyscan16();
}
}
void Delay1ms(uchar z) //@12.000MHz
{
unsigned char i, j;
uchar k;
for(k=z;k>0;k--)
{
i = 12;
j = 169;
do
{
while (--j);
} while (--i);
}
}
void allinit()
{
P2=0X80;
P0=0XFF;//关LED
P2=0XC0;
P0=0XFF;
P2=0XE0;
P0=0XFF;//关数码管
P2=0XA0;
P0=0X00;//关蜂鸣器 继电器
// P2=0XA0;
// P0=0X00;
//
// P2=0XC0;
// P0=0XFF;
// P2=0XE0;
// P0=0XFF;//关数码管
//
// P2=0X80;
// P0=0XFF;
}
void keyscan16()
{
//第一列
P3=0X7F;P4=0XEF;//P44=0;其他为1 管脚转换的过程 P44->P37
temp=P3;
temp=temp&0x0f;//0111 1111 &0000 1111 =0000 1111
if(temp!=0x0f)
{
Delay1ms(5);
temp=P3;
temp=temp&0x0f;//0111 1111 &0000 1111 =0000 1111
if(temp!=0x0f)
{
temp=P3;
switch(temp)
{
case 0x7e :P0=0x00;break;
case 0x7d :P0=0xff;break;
case 0x7b :P0=0x55;break;
case 0x77 :P0=0x0f;break;
}
while(temp!=0x0f)
{
temp=P3;
temp=temp&0x0f;
}
}
}
P3=0XBF;P4=0XFB;//P42=0;管脚转换的过程 P42->P36
temp=P3;
temp=temp&0x0f;//0111 1110 & 0000 1111 = 0000 1110
if(temp!=0x0f)
{
Delay1ms(5);
temp=P3;
temp=temp&0x0f;
if(temp!=0x0f)
{
temp=P3;
switch(temp)
{
case 0xbe :P0=0X0F;break;
case 0xbd :P0=0X00;break;
case 0xbb :P0=0X55;break;
case 0xb7 :P0=0XFF;break;
}
while(temp!=0x0f)
{
temp=P3;
temp=temp&0x0f;
}
}
}
//第三列
P4=0XFF;//恢复P4口
P3=0XDF;
temp=P3;
temp=temp&0x0f;//0111 1110 & 0000 1111 = 0000 1110
if(temp!=0x0f)
{
Delay1ms(5);
temp=P3;
temp=temp&0x0f;
if(temp!=0x0f)
{
temp=P3;
switch(temp)
{
case 0xDe :P0=0XF0;break;
case 0xDd :P0=0XFC;break;
case 0xDb :P0=0XF3;break;
case 0xD7 :P0=0XFF;break;
}
while(temp!=0x0f)
{
temp=P3;
temp=temp&0x0f;
}
}
}
//第四列
P3=0XEF;
temp=P3;
temp=temp&0x0f;//0111 1110 & 0000 1111 = 0000 1110
if(temp!=0x0f)
{
Delay1ms(5);
temp=P3;
temp=temp&0x0f;
if(temp!=0x0f)
{
temp=P3;
switch(temp)
{
case 0xEe :P0=0XF0;break;
case 0xEd :P0=0XFC;break;
case 0xEb :P0=0XF3;break;
case 0xE7 :P0=0XFF;break;
}
while(temp!=0x0f)
{
temp=P3;
temp=temp&0x0f;
}
}
}
}