写一个基于51单片机按键控制流水灯方向的代码
时间: 2024-01-25 19:02:59 浏览: 259
基于51单片机的按键控制流水灯
以下是基于51单片机按键控制流水灯方向的代码:
#include <reg51.h>
sbit LED1 = P0^0;
sbit LED2 = P0^1;
sbit LED3 = P0^2;
sbit LED4 = P0^3;
sbit KEY1 = P1^0;
sbit KEY2 = P1^1;
void delay(unsigned int time) // 延时函数
{
unsigned int i, j;
for (i = time; i > 0; i--)
for (j = 110; j > 0; j--);
}
void main()
{
unsigned char direction = 1; // 定义方向,1为正向,0为反向
unsigned char state = 1; // 定义状态,1为流水灯亮,0为流水灯灭
unsigned char key1_state = 0; // 定义按键1状态,0为未按下,1为按下
unsigned char key2_state = 0; // 定义按键2状态,0为未按下,1为按下
while (1)
{
if (KEY1 == 0) // 检测按键1是否按下
{
delay(10); // 延时去抖动
if (KEY1 == 0)
{
key1_state = 1;
while (KEY1 == 0);
}
}
else
{
key1_state = 0;
}
if (KEY2 == 0) // 检测按键2是否按下
{
delay(10); // 延时去抖动
if (KEY2 == 0)
{
key2_state = 1;
while (KEY2 == 0);
}
}
else
{
key2_state = 0;
}
if (key1_state == 1) // 按键1按下,改变方向
{
direction = !direction;
state = 0; // 流水灯灭
}
if (key2_state == 1) // 按键2按下,改变状态
{
state = !state;
}
if (state == 1) // 流水灯亮
{
if (direction == 1) // 正向流水灯
{
LED1 = 1;
delay(500);
LED1 = 0;
LED2 = 1;
delay(500);
LED2 = 0;
LED3 = 1;
delay(500);
LED3 = 0;
LED4 = 1;
delay(500);
LED4 = 0;
}
else // 反向流水灯
{
LED4 = 1;
delay(500);
LED4 = 0;
LED3 = 1;
delay(500);
LED3 = 0;
LED2 = 1;
delay(500);
LED2 = 0;
LED1 = 1;
delay(500);
LED1 = 0;
}
}
else // 流水灯灭
{
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
}
}
}
阅读全文