51单片机中,如何使用3个按键,分别控制3个LED亮灭?功能:上电灯灭。1
,当按k1时,对应LED1亮;2,按k2时,LED2亮;3,按k3时,LED2灭,LED3亮,再按k2时LED3灭;4,再按k1时,LED2,LED3灭,再按k1时,LE...
,当按k1时,对应LED1亮;2,按k2时,LED2亮;3,按k3时,LED2灭,LED3亮,再按k2时LED3灭;4,再按k1时,LED2,LED3灭,再按k1时,LED1,LED2,LED3全灭,求c程序
展开
展开全部
#include <reg52.h>
typedef unsigned int UINT16;
typedef unsigned char UCHAR;
/************************************************************/
//½Ó¿Ú¶¨Òå
sbit K1 = P1^0;
sbit K2 = P1^1;
sbit K3 = P1^2;
sbit LED1 = P2^0;
sbit LED2 = P2^1;
sbit LED3 = P2^2;
/***********************************************************/
//ÑÓʱº¯Êý
//
//
//
/***********************************************************/
void Delay(UINT16 ui16Dly)
{
UINT16 i,j;
for (i = ui16Dly; i > 0; i--);
for (j = 110; j > 0; j--);
}
/***********************************************************/
//°´¼üɨÃè
//
//
//
/***********************************************************/
UINT16 Key_Scan(void)
{
UINT16 ui16Key;
ui16Key = 0x00;
ui16Key |= (K1 == 0) ? 0x01 : 0;
ui16Key |= (K2 == 0) ? 0x02 : 0;
ui16Key |= (K3 == 0) ? 0x04 : 0;
return (ui16Key);
}
/***********************************************************/
//LED¹Ø
//
//
//
/***********************************************************/
void Led_Off(void)
{
LED1 = 1;
LED2 = 1;
LED3 = 1;
}
/***********************************************************/
//LEDָʾ
//
//
//
/***********************************************************/
void Led_Flg(UINT16 ui16Flg)
{
switch (ui16Flg)
{
case 0: //K1
LED1 = 0;
break;
case 1:
LED2 = 0; //K2
break;
case 2: //K3
LED2 = 1;
LED3 = 0;
break;
case 3: //K2
LED3 = 1;
break;
case 4: //K1
LED2 = 1;
LED3 = 1;
break;
case 5: //K1
LED1 = 1;
LED2 = 1;
LED3 = 1;
break;
default :
LED1 = 1;
LED2 = 1;
LED3 = 1;
break;
}
}
static UINT16 ui16Cnt[3];
static UINT16 ui16Flg;
/***********************************************************/
//Ö÷º¯Êý
//
//
//
/***********************************************************/
void main(void)
{
UINT16 ui16Key,ui16Temp;
ui16Cnt[0] = 0;
ui16Cnt[1] = 0;
ui16Cnt[2] = 0;
ui16Flg = 0x00;
Led_Off();
ui16Key = Key_Scan();
ui16Flg = 0xff;
while (1)
{
//°´¼ü
ui16Temp = Key_Scan();
if (ui16Key != ui16Temp)
{
Delay(5);
ui16Temp = Key_Scan();
if (ui16Key != ui16Temp)
{
ui16Key = ui16Temp;
}
}
//K1
if (ui16Temp & 0x01)
{
switch (ui16Cnt[0])
{
case 0:
ui16Flg = 0;
break;
case 1:
ui16Flg = 4;
break;
case 2:
ui16Flg = 5;
break;
}
while (ui16Temp & 0x01) ui16Temp = Key_Scan();
ui16Cnt[0]++;
if (ui16Cnt[0] > 2) ui16Cnt[0] = 0;
}
//K2
if (ui16Temp & 0x02)
{
if (ui16Cnt[1] > 0) ui16Flg = 3;
else ui16Flg = 1;
while (ui16Temp & 0x02) ui16Temp = Key_Scan();
ui16Cnt[1]++;
if (ui16Cnt[1] > 1) ui16Cnt[1] = 0;
}
//K3
if (ui16Temp & 0x04)
{
ui16Flg = 2;
while (ui16Temp & 0x04) ui16Temp = Key_Scan();
}
//LED
Led_Flg(ui16Flg);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询