单片机独立键盘控制LED灯,程序问题

2025年03月23日 02:07
有3个网友回答
网友(1):

#include
#include
#define uint unsigned int
#define uchar unsigned char

void yanshi (uint n)
{
uint j, i;
for (j = n; j > 0; j--) for (i = 110; i > 0; i--);
}

uchar anjian ()
{
uchar i;

//这里想实现当某灯被点亮后,如果一定时间
//没有其他灯被点亮,就自动熄灭,

while (1) {
if (P1 != 255) { //有按键?
yanshi(10); //延时消抖
if (P1 != 255) return P1;//返回键盘的状态
}

else { //没有按
i = 0;
while (P1 == 255) { //没有按就循环
yanshi(10); //延时
i++;
if (i == 200) { P0 = 0; i = 199;}//延了200就关灯
}
}
}
}

void main()
{
uchar dian;
P0 = 0x00;
while (1) {
// P0 = anjian();
dian = anjian();
switch (dian) {
case (0xfe): P0 |= 0x01; break;
case (0xfd): P0 |= 0x02; break;
case (0xfb): P0 |= 0x04; break;
case (0xf7): P0 |= 0x08; break;
case (0xef): P0 |= 0x10; break;
case (0xdf): P0 |= 0x20; break;
case (0xbf): P0 |= 0x40; break;
case (0x7f): P0 |= 0x80; break;
default : break;
}
}
}
试试看。

网友(2):

switch()语句里有问题
switch(a)作为条件选择语句,其参数a具备多值,并在case里匹配到相应的数值进行相应功能实现。
但你的程序switch(key!=0xff)里,Key!=0xff是一条判断语句,其值为1(若你按下了按键的话),即这条语句实际上变成了switch(1),请问有什么效果呢?
如果需要实现你的功能,不要偷懒啦,老老实实这样写:
...
delay(5);
if(key!=0xff)
{
switch(Key)
{
case ...break;
.......
}
}
请采纳。

网友(3):

5000,延时也就几十毫米,基本没有什么感觉。