CT107D竞赛板独立按键的基础与应用
COM3(j5) 选择2 3引脚为独立按键 选择 1 2引脚为矩阵按键
在按键中 一方接地 一方接芯片
当按键按下时 芯片的一方会从高低平变成低电平
这时就可知判定按键是否按下
需注意按键按下时具有抖动
会影响实际效果
这时就需要消抖
按后延迟20毫秒
再进行程序操作
再进行按键判定
按键判定:while(所需判定按键);
列: while(S7==0);
基本代码:
include<STC15F2K60S2.H>
sbit S7 = P3^0;//定义所需按键
sbit S6 = P3^1;
sbit S5 = P3^2;
sbit S4 = P3^3;
sbit L1 = P0^0;//定义所需LED
sbit L2 = P0^1;
sbit L3 = P0^2;
sbit L4 = P0^3;
sbit L5 = P0^4;
sbit L6 = P0^5;
void SelectHC573(unsigned char n)//锁存器选择
{
switch(n)
{
case 4:
P2 = (P2 & 0x1f) | 0x80;
break;
case 5:
P2 = (P2 & 0x1f) | 0xa0;
break;
case 6:
P2 = (P2 & 0x1f) | 0xc0;
break;
case 7:
P2 = (P2 & 0x1f) | 0xe0;
break;
}
}
void Delayk(unsigned char t)//二次延迟 (将月份动态显示)
{
while(t--);
}
void ScanKeys_Alone()独立按键
{
if(S7== 0)
{
Delayk(100);//消抖延迟
if(S7== 0)
{
L1 = 0;
while(S7==0);//按键判定
L1 = 1;
}
}
if(S6== 0)
{
Delayk(100);
if(S6== 0)
{
L2 = 0;
while(S6==0);
L2 = 1;
}
}
if(S5== 0)
{
Delayk(100);
if(S5== 0)
{
L3 = 0;
while(S5==0);
L3 = 1;
}
}
if(S4== 0)
{
Delayk(100);
if(S4== 0)
{
L4 = 0;
while(S4==0);
L4 = 1;
}
}
}
void f ()//初始化
{
SelectHC573(5);
P0=0x00;
SelectHC573(4);
P0=0xff;
}
void main ()
{
f ();
SelectHC573(4);
while(1)
{
ScanKeys_Alone();
}
}
进阶代码:
include<STC15F2K60S2.H>
sbit S7 = P3^0;
sbit S6 = P3^1;
sbit S5 = P3^2;
sbit S4 = P3^3;
sbit L1 = P0^0;
sbit L2 = P0^1;
sbit L3 = P0^2;
sbit L4 = P0^3;
sbit L5 = P0^4;
sbit L6 = P0^5;
void SelectHC573(unsigned char n)
{
switch(n)
{
case 4:
P2 = (P2 & 0x1f) | 0x80;
break;
case 5:
P2 = (P2 & 0x1f) | 0xa0;
break;
case 6:
P2 = (P2 & 0x1f) | 0xc0;
break;
case 7:
P2 = (P2 & 0x1f) | 0xe0;
break;
}
}
void Delayk(unsigned char t)
{
while(t--);
}
unsigned char stat_k = 0;//定义变量(状态选定)
void ScanKeys_Alone()
{
if(S7== 0)//状态1 按下s7后改变s4,s5的亮灯方式位置
{
Delayk(100);
if(S7== 0)
{
if(stat_k == 0)
{
L1=0;
stat_k = 1;
}
else if (stat_k== 1)
{
L1= 1;
stat_k = 0;
}
while(S7==0);
}
}
if(S6== 0)//状态2 当按下s6后改变s4,s5的亮灯位置
{
Delayk(100);
if(S6== 0)
{
if(stat_k ==0)
{
L2=0;
stat_k =2;
}
else if(stat_k ==2)
{
L2 = 1;
stat_k = 0;
}
while(S6==0);
}
}
if(S5== 0)
{
Delayk(100);
if(S5== 0)
{
if(stat_k ==1)
{
L3 = 0;
while(S5 == 0);
L3 = 1;
}
else if(stat_k ==2)
{
L5 = 0;
while(S5 == 0);
L5 = 1;
}
}
}
if(S4== 0)
{
Delayk(100);
if(S4== 0)
{
if(stat_k ==1)
{
L4 = 0;
while(S4==0);
L4 = 1;
}
else if(stat_k ==2)
{
L6 = 0;
while(S4==0);
L6 = 1;
}
}
}
}
void f ()
{
SelectHC573(5);
P0=0x00;
SelectHC573(4);
P0=0xff;
}
void main ()
{
f ();
SelectHC573(4);
while(1)
{
ScanKeys_Alone();
}
}