51单片机用四个按键控制8个led灯的点亮、熄灭、变亮、变暗的代码
时间: 2023-10-20 12:19:47 浏览: 90
以下是用四个按键控制8个LED灯的点亮、熄灭、变亮、变暗的代码。其中,按键K1用于控制LED1~LED4,按键K2用于控制LED5~LED8,按键K3用于变亮,按键K4用于变暗。
```c
#include <reg52.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 K1 = P3^0;
sbit K2 = P3^1;
sbit K3 = P3^2;
sbit K4 = P3^3;
void main()
{
unsigned char led_status = 0x00;
unsigned char k1_status = 0;
unsigned char k2_status = 0;
unsigned char k3_status = 0;
unsigned char k4_status = 0;
while(1)
{
// 获取按键状态
k1_status = K1;
k2_status = K2;
k3_status = K3;
k4_status = K4;
// 点亮LED灯
if(k1_status == 0)
{
led_status |= 0x0f;
}
if(k2_status == 0)
{
led_status |= 0xf0;
}
// 熄灭LED灯
if(k1_status == 0 && k2_status == 0)
{
led_status = 0x00;
}
// 变亮
if(k3_status == 0)
{
if((led_status & 0x0f) != 0x0f) // LED1~LED4还没有全部点亮
{
led_status <<= 1;
led_status |= 0x01;
}
if((led_status & 0xf0) != 0xf0) // LED5~LED8还没有全部点亮
{
led_status >>= 1;
led_status |= 0x80;
}
}
// 变暗
if(k4_status == 0)
{
if((led_status & 0x0f) != 0x00) // LED1~LED4还没有全部熄灭
{
led_status >>= 1;
led_status &= 0x7f;
}
if((led_status & 0xf0) != 0x00) // LED5~LED8还没有全部熄灭
{
led_status <<= 1;
led_status &= 0xfe;
}
}
// 输出LED状态
LED1 = (led_status & 0x01) ? 1 : 0;
LED2 = (led_status & 0x02) ? 1 : 0;
LED3 = (led_status & 0x04) ? 1 : 0;
LED4 = (led_status & 0x08) ? 1 : 0;
LED5 = (led_status & 0x10) ? 1 : 0;
LED6 = (led_status & 0x20) ? 1 : 0;
LED7 = (led_status & 0x40) ? 1 : 0;
LED8 = (led_status & 0x80) ? 1 : 0;
}
}
```
需要注意的是,这里使用了位运算来控制LED的状态,可以提高代码的效率。同时,需要进行按键消抖处理,否则会出现按键抖动导致的误触发。