51单片机按键流水灯代码
时间: 2023-11-09 10:08:47 浏览: 154
以下是51单片机按键流水灯的代码,供您参考:
```
#include <reg52.h>
sbit LED1 = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;
sbit LED4 = P1^3;
sbit KEY1 = P3^1;
sbit KEY2 = P3^0;
void delay(unsigned int xms);
void main()
{
unsigned char i = 0;
while(1)
{
if(KEY1 == 0)
{
delay(10);
if(KEY1 == 0)
{
i++;
if(i > 3)
{
i = 0;
}
}
while(KEY1 == 0);
}
if(KEY2 == 0)
{
delay(10);
if(KEY2 == 0)
{
i--;
if(i < 0)
{
i = 3;
}
}
while(KEY2 == 0);
}
switch(i)
{
case 0:
LED1 = 1;
LED2 = 0;
LED3 = 0;
LED4 = 0;
break;
case 1:
LED1 = 0;
LED2 = 1;
LED3 = 0;
LED4 = 0;
break;
case 2:
LED1 = 0;
LED2 = 0;
LED3 = 1;
LED4 = 0;
break;
case 3:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 1;
break;
default:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
break;
}
}
}
void delay(unsigned int xms)
{
unsigned char i, j;
for(i = xms; i > 0; i--)
{
for(j = 110; j > 0; j--);
}
}
```
该代码使用了4个LED灯和2个按键,通过按键来控制LED的流水效果。按下KEY1则流水方向向右,按下KEY2则流水方向向左。您可以根据自己的需要进行修改。
阅读全文