51单片机用一个按键控制八个灯,四种形态
时间: 2023-05-16 19:05:02 浏览: 353
可以使用二进制编码的方式实现。首先将八个灯的状态用一个八位的二进制数表示,然后用一个按键来控制这个二进制数的值。每按一次按键,二进制数加一,当二进制数的值大于等于四时,灯的状态就会发生变化,形成四种不同的形态。以下是示例代码:
```
#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 KEY = P3^2;
void delay(unsigned int t)
{
while(t--);
}
void main()
{
unsigned char state = 0;
unsigned char last_key = 1;
while(1)
{
if(KEY == 0 && last_key == 1)
{
state++;
if(state >= 4)
{
state = 0;
}
}
last_key = KEY;
switch(state)
{
case 0:
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
break;
case 1:
LED1 = 1;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
break;
case 2:
LED1 = 1;
LED2 = 1;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
LED8 = 0;
break;
case 3:
LED1 = 1;
LED2 = 1;
LED3 = 1;
LED4 = 1;
LED5 = 1;
LED6 = 1;
LED7 = 1;
LED8 = 1;
break;
}
delay(1000);
}
}
```
这段代码使用 P1 口控制八个 LED 灯,P3.2 口接一个按键。每按一次按键,灯的状态就会发生变化。
阅读全文