用51单片机一个按键控制八个灯,让八个灯有不同形态的亮法,另一个按键控制过程的暂停和继续
时间: 2023-05-16 11:05:23 浏览: 136
这个问题可以通过编写一个简单的程序来实现。首先,我们需要定义一个变量来存储当前灯的状态,然后在按下按键时,将变量的值加1,然后根据变量的值来控制灯的亮灭。我们还需要定义一个变量来存储当前程序的状态,以便在按下另一个按键时暂停或继续程序的执行。
以下是一个简单的示例程序:
```
#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 = P2^0;
sbit KEY2 = P2^1;
unsigned char led_state = 0;
unsigned char program_state = 1;
void delay(unsigned int t)
{
unsigned int i, j;
for(i = 0; i < t; i++)
for(j = 0; j < 100; j++);
}
void main()
{
while(1)
{
if(KEY1 == 0)
{
led_state++;
if(led_state > 7)
led_state = 0;
delay(50);
}
if(KEY2 == 0)
{
program_state = !program_state;
delay(50);
}
if(program_state)
{
switch(led_state)
{
case 0:
LED1 = 1;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
break;
case 1:
LED1 = 1;
LED2 = 1;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
break;
case 2:
LED1 = 1;
LED2 = 1;
LED3 = 1;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
break;
case 3:
LED1 = 1;
LED2 = 1;
LED3 = 1;
LED4 = 1;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
break;
case 4:
LED1 = 1;
LED2 = 1;
LED3 = 1;
LED4 = 1;
LED5 = 1;
LED6 = 0;
LED7 = 0;
LED8 = 0;
break;
case 5:
LED1 = 1;
LED2 = 1;
LED3 = 1;
LED4 = 1;
LED5 = 1;
LED6 = 1;
LED7 = 0;
LED8 = 0;
break;
case 6:
LED1 = 1;
LED2 = 1;
LED3 = 1;
LED4 = 1;
LED5 = 1;
LED6 = 1;
LED7 = 1;
LED8 = 0;
break;
case 7:
LED1 = 1;
LED2 = 1;
LED3 = 1;
LED4 = 1;
LED5 = 1;
LED6 = 1;
LED7 = 1;
LED8 = 1;
break;
}
}
}
}
```
阅读全文