独立按键
1.独立按键
相当于电子开关,相同一边的两个引脚始终导通。按下四个引脚相连,松手两边分别连接。
(开发板中独立按键)原理图
K1接P31,K2接P30,K3接P32,K4接P33.
应知应会部分
如何控制寄存器中的单独一位
查头文件P2_0是P2寄存器中最低位,对应第一个LED。
C51数据运算
.
0001 1000 & 0010 1010 -> 0000 1000 //按位与
0001 1000 | 0010 1010 -> 0011 1010//按位或
0001 1000 ^ 0010 1010 -> 0011 0010//按位异或
~0001 1000 -> 1110 0111
C51基本语句
2.如何实现按键控制led1亮灭
// An highlighted block
#include <REGX52.H>
void main()
{
while(1)
{
if(P3_1==0)//读P31寄存器,第一个按键
{
P2_0=0;
}//按下按键时,灯亮
else
{
P2_0=1;
}//不按按键时,灯灭
}
}
3.独立按键控制LED状态
消除按键抖动
// An highlighted block
#include <REGX52.H>
void Delay(unsigned int xms) //@12.000MHz延时函数
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}
void main()
{
while(1)
{
if (P3_1==0)//如果按键按下
{
Delay(20);//消抖20ms
while(P3_1==0);//检测松手
Delay(20);
P2_0 = ~ P2_0;//灯灭
}
}
}
4.独立按键控制LED显示二进制
// An highlighted block
#include <REGX52.H>
void Delay(unsigned int xms) //@12.000MHz延时函数
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}
void main()
{
unsigned char LEDnum=0;//P2一开始都默认高电平,1111 1111 直接对P2口径操作会溢出,自定义变量,一般用unsigned char 表示一个寄存器
while(1)
{
if (P3_1==0)//如果按键按下
{
Delay(20);//消抖20ms
while(P3_1==0);
Delay(20);
LEDnum++;
P2=~LEDnum;//P2取反
}
}
}
5.独立按键控制LED移位
移位的状态:
0000 0001 0x01<<0
0000 0010 0x01<<1
0000 0100 0x01<<2
0000 1000 0x01<<3
.
.
.
.
1000 0000 0x01<<7
左移一位
// An highlighted block
#include <REGX52.H>
void Delay(unsigned int xms);//声明.Delay函数要放在前面,不放在前面要先声明。
unsigned char LEDnum;
void main()
{
P2=~0x01;//初始化
while(1)
{
if (P3_1==0)//如果按键按下
{
Delay(20);//消抖20ms
while(P3_1==0);
Delay(20);
LEDnum++;
if(LEDnum>=8)
LEDnum=0;
P2=~(0x01<<LEDnum);//P2是LED左移LEDnum位,也要取反
}
}
}
void Delay(unsigned int xms) //@12.000MHz延时函数
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}
一个按键左移一个按键右移
其余参考上面,改动部分如下.
// An highlighted block
#include <REGX52.H>
void Delay(unsigned int xms) ;
unsigned char LEDnum;
void main()
{
P2=~0x01;
while(1)
{
if(P3_1==0)
{
Delay(20);
while(P3_1==0);
Delay(20);
LEDnum++;
if(LEDnum>=8)
LEDnum=0;
P2=~(0x01<<LEDnum);
}
{
if (P3_0==0)
{
Delay(20);
while(P3_0==0);
Delay(20);
if (LEDnum==0)
LEDnum=7;
else
LEDnum--;
P2=~(0x01<<LEDnum);
}
}
}
}
void Delay(unsigned int xms)
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}