02-独立按键控制led
按键的抖动
对于机械开关,当机械触点断开、闭合时,由于机械触点的弹性作用,一个开关在闭合时不会马上稳定地接通,在断开时也不会一下子断开,所以在开关闭合及断开的瞬间会伴随一连串的抖动
一、控制led
的亮灭
按住亮松开灭
#include <REGX52.H>
void main()
{
while(1)
{
if(P3_1 == 0)
{
P2_7 = 0;
}
else if(P3_1 == 1)
{
P2_7 = 1;
}
}
}
二、控制led
的状态
按一次亮,再按一次灭,再按一次亮,再按一次灭...
#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()
{
P2_7 = 1;
while(1)
{
if(P3_1 == 0)
{
Delay(20); // 延迟消抖
while(P3_1 == 0);
Delay(20); // 延迟消抖
P2_7 = ~P2_7; // 每次状态取反
}
}
}
三、控制led的二进制显示
0~255的二进制显示,亮表示1,灭表示0。每次按下显示的值加一
#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 chLedNum = 0;
unsigned char chTmp = 0;
P2 = 0xFF;
while(1)
{
if(P3_1 == 0)
{
Delay(20);
while(P3_1 == 0);
Delay(20);
chLedNum++;
P2 = ~chLedNum;
chTmp = P2_0;
P2_0 = P2_7;
P2_7 = chTmp;
chTmp = P2_1;
P2_1 = P2_6;
P2_6 = chTmp;
chTmp = P2_2;
P2_2 = P2_5;
P2_5 = chTmp;
chTmp = P2_3;
P2_3 = P2_4;
P2_4 = chTmp;
}
}
}
四、控制led的移位
每按一次,从右向左移一位
#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 chLedNum = 0x80;
while(1)
{
if(P3_1 == 0)
{
Delay(20);
while(P3_1 == 0);
Delay(20);
P2 = ~chLedNum;
chLedNum /= 2;
if(chLedNum == 0)
{
chLedNum = 0x80;
}
}
}
}
标签:02,P2,led,--,unsigned,Delay,while,按键,xms
From: https://www.cnblogs.com/yljblogs/p/17880205.html