在51单片机实验上用c语言编程实现独立按键对LED流水灯显示的控制要求最多使用单片机实验板上三个独立按键控制由八个LED组成的流水灯的显示,实现四种不同样式的循环
时间: 2023-05-15 17:08:12 浏览: 86
非常感谢您的问题!以下是我对您的问题的回答:
您可以使用以下代码实现独立按键对LED流水灯显示的控制:
```
#include <reg51.h>
sbit LED1 = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;
sbit LED4 = P1^3;
sbit LED5 = P1^4;
sbit LED6 = P1^5;
sbit LED7 = P1^6;
sbit LED8 = P1^7;
sbit KEY1 = P3^0;
sbit KEY2 = P3^1;
sbit KEY3 = P3^2;
void delay(unsigned int i)
{
while(i--);
}
void main()
{
unsigned char mode = 0;
unsigned char key1_state = 0;
unsigned char key2_state = 0;
unsigned char key3_state = 0;
while(1)
{
if(KEY1 == 0)
{
delay(1000);
if(KEY1 == 0)
{
key1_state = !key1_state;
}
while(!KEY1);
}
if(KEY2 == 0)
{
delay(1000);
if(KEY2 == 0)
{
key2_state = !key2_state;
}
while(!KEY2);
}
if(KEY3 == 0)
{
delay(1000);
if(KEY3 == 0)
{
key3_state = !key3_state;
}
while(!KEY3);
}
switch(mode)
{
case 0:
LED1 = 1;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
delay(100);
break;
case 1:
LED1 = 0;
LED2 = 1;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
delay(100);
break;
case 2:
LED1 = 0;
LED2 = 0;
LED3 = 1;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
delay(100);
break;
case 3:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 1;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
delay(100);
break;
case 4:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 1;
LED6 = 0;
LED7 = 0;
LED8 = 0;
delay(100);
break;
case 5:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 1;
LED7 = 0;
LED8 = 0;
delay(100);
break;
case 6:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 1;
LED8 = 0;
delay(100);
break;
case 7:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 1;
delay(100);
break;
default:
break;
}
if(key1_state == 1)
{
mode++;
if(mode > 7)
{
mode = 0;
}
key1_state = 0;
}
if(key2_state == 1)
{
delay(1000);
if(key2_state == 1)
{
mode = 0;
}
key2_state = 0;
}
if(key3_state == 1)
{
delay(1000);
if(key3_state == 1)
{
mode = 7;
}
key3_state = 0;
}
}
}
```
这段代码实现了使用三个独立按键控制由八个LED组成的流水灯的显示,实现四种不同样式的循环。其中,按下按键1可以切换不同的循环模式,按下按键2可以重新开始循环,按下按键3可以跳转到最后一个LED亮起的模式。
阅读全文