单片机按键控制流水灯代码
时间: 2023-09-03 13:16:41 浏览: 221
单片机 按键控制流水灯
好的,这是一个基于C语言的单片机按键控制流水灯的代码示例:
```c
#include <reg51.h>
sbit LED1 = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;
sbit LED4 = P1^3;
sbit KEY1 = P3^2;
sbit KEY2 = P3^3;
void delay(unsigned int time)
{
while(time--);
}
void main()
{
unsigned char cnt = 0;
unsigned char dir = 0;
unsigned int speed = 50000;
KEY1 = 1;
KEY2 = 1;
while(1)
{
if(KEY1 == 0)
{
delay(1000);
if(KEY1 == 0)
{
dir = !dir; //改变方向
}
while(KEY1 == 0);
}
if(KEY2 == 0)
{
delay(1000);
if(KEY2 == 0)
{
speed /= 2; //加快速度
}
while(KEY2 == 0);
}
if(speed < 1000)
{
speed = 50000; //速度上限
}
if(cnt == 0)
{
LED1 = 1;
LED4 = 0;
}
else if(cnt == 1)
{
LED2 = 1;
LED1 = 0;
}
else if(cnt == 2)
{
LED3 = 1;
LED2 = 0;
}
else
{
LED4 = 1;
LED3 = 0;
}
if(dir == 0)
{
cnt = (cnt + 1) % 4;
}
else
{
cnt = (cnt + 3) % 4;
}
delay(speed);
}
}
```
这段代码是基于8051单片机的,通过P1口控制LED灯的亮灭,P3口读取按键状态。在主循环中不断扫描按键状态,根据按键的不同操作改变流水灯的运行方向和速度。
阅读全文