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

#include <reg51.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
void yanshi(uint n);
uchar anjian ();
uchar dian ;
#define js P1
#define ld P0
void main(){
ld=0x00;
while (1){

switch (anjian()){
case (0xfe):
ld = 0x01;
break;
case (0xfd):
ld =0x02;
break;
case (0xfb):
ld =0x04;
break;
case (0xf7):
ld =0x08;
break;
case (0xef):
ld =0x10;
break;
case (0xdf):
ld =0x20;
break;
case (0xbf):
ld =0x40;
break;
case (0x7f):
ld =0x80;
break;
default :
break;
}
}
}
void yanshi (uint n){
uint j,i;
for (j=n;j>0;j--)
for (i=110;i>0;i--);
}
uchar anjian ()
{
uchar i,j=5000;
while (j--) //这里想实现当某灯被点亮后,如果一定时间
{ //没有其他灯被点亮,就自动熄灭,为什么我这个循环毫无存在感,有没有它一样
if (js==ld) //大神帮忙看看那里不对了?
{
if (j==0){
ld=0x00;
break;
}
}
else
break;
}
if( js != 0x00 )
{
yanshi(100);
if( js != 0x00 )
{
dian=js;
i=0;
while ((i<50)&&(js!=0x00))
{
yanshi();
i++;
}
}
}
return dian;
}

#include <reg51.h>
#include <intrins.h>
#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;
}
}
}
试试看。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-08-01
switch()语句里有问题
switch(a)作为条件选择语句,其参数a具备多值,并在case里匹配到相应的数值进行相应功能实现。
但你的程序switch(key!=0xff)里,Key!=0xff是一条判断语句,其值为1(若你按下了按键的话),即这条语句实际上变成了switch(1),请问有什么效果呢?
如果需要实现你的功能,不要偷懒啦,老老实实这样写:
...
delay(5);
if(key!=0xff)
{
switch(Key)
{
case ...break;
.......
}
}
请采纳。追问

大哥,您说的这是哪跟哪啊?你用的变量也和我的不一样,您确定没回答错问题?

第2个回答  2014-08-01
5000,延时也就几十毫米,基本没有什么感觉。追问

这样说来,灯亮一下就会马上灭掉,事实上是它一直亮着呢

追答

要实现你的功能,这样做是不行的,你可以用一个定时器来做这个一定时间未有其他按键的过程控制,否则是无法捕捉到这个在延时过程中检测按键的。