51单片机1个按键控制4个LED灯代码
时间: 2024-01-25 10:02:25 浏览: 111
以下是51单片机1个按键控制4个LED灯的代码,使用Keil C编译器:
```
#include <reg51.h>
sbit KEY = P1^0;
sbit LED1 = P2^0;
sbit LED2 = P2^1;
sbit LED3 = P2^2;
sbit LED4 = P2^3;
void delay(unsigned int t)
{
while(t--);
}
void main()
{
unsigned char state = 0;
while(1)
{
if(KEY == 0)
{
delay(1000);
if(KEY == 0)
{
state++;
if(state == 5)
{
state = 0;
}
switch(state)
{
case 0:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
break;
case 1:
LED1 = 1;
LED2 = 0;
LED3 = 0;
LED4 = 0;
break;
case 2:
LED1 = 0;
LED2 = 1;
LED3 = 0;
LED4 = 0;
break;
case 3:
LED1 = 0;
LED2 = 0;
LED3 = 1;
LED4 = 0;
break;
case 4:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 1;
break;
}
}
while(KEY == 0);
}
}
}
```
这段代码通过P1口的一个按键控制P2口的四个LED灯的亮灭,分别对应按键按下的不同状态。具体实现方式是通过一个状态变量state记录当前状态,每次按下按键切换状态并控制LED灯的亮灭。
阅读全文