C51编写一个按键控制不同花样的流水灯
以下是一个使用C51编写的按键控制不同花样的流水灯的示例代码:
#include <reg51.h>
sbit LED = P2^0; // 定义流水灯连接的引脚
sbit Button = P3^2; // 定义按键连接的引脚
void delay(unsigned int ms) {
unsigned int i, j;
for(i = 0; i < ms; i++)
for(j = 0; j < 114; j++);
}
void main() {
unsigned int pattern = 0; // 用于存储当前的花样
unsigned int counter = 0; // 用于计数按键按下的次数
while(1) {
if(Button == 0) { // 检测按键是否按下
delay(20); // 延迟一段时间,避免按键抖动造成多次按下
if(Button == 0) {
counter++; // 按键按下次数加一
while(!Button); // 等待按键释放
}
}
if(counter == 1) { // 第一次按下按键
pattern = 0x01; // 设置花样为第一种
} else if(counter == 2) { // 第二次按下按键
pattern = 0x0F; // 设置花样为第二种
} else if(counter == 3) { // 第三次按下按键
pattern = 0xAA; // 设置花样为第三种
} else if(counter == 4) { // 第四次按下按键
pattern = 0xFF; // 设置花样为第四种
} else { // 按键按下次数超过四次,重置为初始状态
counter = 0; // 重置计数器
pattern = 0x00; // 设置花样为初始状态
}
LED = pattern; // 输出花样到流水灯
delay(500); // 延迟一段时间,控制流水灯的速度
}
}
在上述代码中,我们使用P2^0引脚连接了流水灯,P3^2引脚连接了按键。按下按键时,通过计数器来切换不同的花样,然后将花样输出到流水灯上。其中,delay函数用于控制流水灯的速度,可以根据需要进行调整
原文地址: http://www.cveoy.top/t/topic/hLfj 著作权归作者所有。请勿转载和采集!