编写一段c语言代码,实现按键一控制正向流水灯 按键二控制反向流水灯 按键三控制流水灯的数量(1个,2个,3个)
时间: 2023-05-27 19:06:08 浏览: 114
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit LED1 = P2^0;
sbit LED2 = P2^1;
sbit LED3 = P2^2;
sbit Key1 = P3^0;
sbit Key2 = P3^1;
sbit Key3 = P3^2;
void delay(uint xms) //延时函数
{
uint i, j;
for(i=xms; i>0; i--)
for(j=110; j>0; j--);
}
void main()
{
uchar mode = 1; //默认流水灯数量为1
uchar dir = 1; //默认正向流水灯
while(1)
{
if(Key1 == 0) //按键1:正向流水灯
{
delay(10); //消抖
if(Key1 == 0)
{
dir = 1; //正向流水灯
mode = 1; //流水灯数量为1
while(!Key1); //等待按键松开
}
}
if(Key2 == 0) //按键2:反向流水灯
{
delay(10); //消抖
if(Key2 == 0)
{
dir = 0; //反向流水灯
mode = 1; //流水灯数量为1
while(!Key2); //等待按键松开
}
}
if(Key3 == 0) //按键3:流水灯数量
{
delay(10); //消抖
if(Key3 == 0)
{
mode++; //流水灯数量加1
if(mode > 3) mode = 1; //循环切换
while(!Key3); //等待按键松开
}
}
if(mode == 1) //流水灯数量为1
{
if(dir) //正向流水灯
{
LED1 = 1; delay(500); LED1 = 0;
}
else //反向流水灯
{
LED1 = 1; delay(500); LED1 = 0;
}
}
else if(mode == 2) //流水灯数量为2
{
if(dir) //正向流水灯
{
LED1 = 1; delay(250); LED1 = 0;
LED2 = 1; delay(250); LED2 = 0;
}
else //反向流水灯
{
LED2 = 1; delay(250); LED2 = 0;
LED1 = 1; delay(250); LED1 = 0;
}
}
else //流水灯数量为3
{
if(dir) //正向流水灯
{
LED1 = 1; delay(167); LED1 = 0;
LED2 = 1; delay(167); LED2 = 0;
LED3 = 1; delay(166); LED3 = 0;
}
else //反向流水灯
{
LED3 = 1; delay(166); LED3 = 0;
LED2 = 1; delay(167); LED2 = 0;
LED1 = 1; delay(167); LED1 = 0;
}
}
}
}
```
阅读全文