谢谢你的回复,我按照你的思路改了一下 我的程序,还是不行,短按键按下没有反应了,和我以前想的方法相近,不知道是不是我理解错了,下面是我修改后的程序:
#include<reg51.h>
sfr P5 = 0XC8;
#define u8 unsigned char
#define u16 unsigned int
#define u32 unsigned long
sbit LEDR = P3^1;
sbit LEDG = P5^5;
sbit LEDB = P3^0;
sbit LEDM = P3^2;
sbit KEY = P3^3;
u8 sysTim; //系统时基
u8 keyProcTim; //按键处理时间
u8 ledProcTim; //LED灯处理时间
u8 keyState; // 按键状态
u8 keyDownCnt; //按键按下计数器
u8 keyShort; //短按键标志
u8 keyLong; //长按键标志
u8 ledState = 0; //led状态
u8 ledon; //开机标志,开机为1
u8 ledmode; //led工作模式
u8 val=0; //红,黄,绿,青,兰,紫,白
//u8 code LED_TEB[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
//u8 LOOP_TEMP=0;
void key_Proc();
void led_Proc();
void main()
{
LEDR = 0;
LEDG = 0;
LEDB = 0;
ledState = 0;
EA = 1;
TMOD = 0X01;
TH0 = 0XFC;
TL0 = 0X66;
ET0 = 1;
TR0 = 1;
while(1)
{
key_Proc();
led_Proc();
}
}
void key_Proc()
{
if(sysTim-keyProcTim >= 20) //20ms扫描一次按键
{
keyProcTim = sysTim;
switch(keyState)
{
case 0: //检测有按键按下
if(!KEY)
{
keyDownCnt = 0;
keyState = 1;
}
break;
case 1: //消抖和短按键确认
if(!KEY)
{
keyDownCnt++;
if(keyDownCnt >= 50) //20ms扫描一次,
//扫描50次即:50*20=1000ms长按键(500ms以上)
{
keyLong = 1; //长按键标志,长按键按下
keyState = 2; //按键状态标志为2
}
}
else
{
if(keyDownCnt != 0) //短按键
{
keyShort = 1; //短按键标志,短按键按下
keyState = 0; //按键状态标志为0
}
}
break;
default: //case 2: //等待按键释放
if(KEY)
{
keyLong = 0; //长按键标志,长按键没有按下
keyState = 0; //按键状态为0
}
break;
}
}
if(1==keyShort) //短按键处理
{
keyShort = 0;
ledState = 1; //led状态1
}
if(1==keyLong) //长按键处理
{
keyLong = 0;
ledState = 10; //led状态2
}
}
void led_Proc()
{
if(1==ledon) //开灯
{
if(ledState==1) //led状态1,短按键
{
// ledState = 0;
// LEDR = 0;
// LEDB = 0;
// LEDG = 1;
val++;
if(val>6)
val=0;
switch(val)
{
case 0 :LEDR = 1;LEDG = 1;LEDB = 1;break; //白
case 1 :LEDR = 1;LEDG = 0;LEDB = 0;break;
case 2 :LEDR = 1;LEDG = 1;LEDB = 0;break;
case 3 :LEDR = 0;LEDG = 1;LEDB = 0;break;
case 4 :LEDR = 0;LEDG = 1;LEDB = 1;break;
case 5 :LEDR = 0;LEDG = 0;LEDB = 1;break;
case 6 :LEDR = 1;LEDG = 0;LEDB = 1;break;
}
}
}
if(10==ledState) //led状态2,长按键
{
ledState = 0;
if(0==ledon) //如果在关灯
{
ledon = 1; //就打打开灯
LEDR = 1;
LEDG = 1;
LEDB = 1;
}
else //如何在开灯
{
ledon = 0; //就关灯
LEDR = 0;
LEDG = 0;
LEDB = 0;
}
}
}
void interruptTimer0() interrupt 1
{
TH0 = 0XFC;
TL0 = 0X66;
sysTim++;
} |