用三个按键控制led流水灯,呼吸灯,跑马灯三种状态
时间: 2023-07-02 09:05:20 浏览: 292
以下是一个基于 Arduino 的示例代码,使用三个按钮控制 LED 流水灯、呼吸灯和跑马灯三种状态:
```
// 定义引脚
const int BUTTON1_PIN = 2;
const int BUTTON2_PIN = 3;
const int BUTTON3_PIN = 4;
const int LED_PIN = 5;
// 定义状态
enum State {
STATE_FLOWING,
STATE_BREATHING,
STATE_RUNNING
};
// 初始化状态
State state = STATE_FLOWING;
void setup() {
// 设置引脚模式
pinMode(BUTTON1_PIN, INPUT_PULLUP);
pinMode(BUTTON2_PIN, INPUT_PULLUP);
pinMode(BUTTON3_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
switch (state) {
case STATE_FLOWING:
flowing();
break;
case STATE_BREATHING:
breathing();
break;
case STATE_RUNNING:
running();
break;
}
// 检测按钮状态
if (digitalRead(BUTTON1_PIN) == LOW) {
state = STATE_FLOWING;
} else if (digitalRead(BUTTON2_PIN) == LOW) {
state = STATE_BREATHING;
} else if (digitalRead(BUTTON3_PIN) == LOW) {
state = STATE_RUNNING;
}
}
void flowing() {
// LED 流水灯,每隔 100 毫秒亮一个 LED
digitalWrite(LED_PIN, HIGH);
delay(100);
digitalWrite(LED_PIN, LOW);
delay(100);
}
void breathing() {
// LED 呼吸灯,每隔 10 毫秒改变亮度
for (int i = 0; i < 255; i++) {
analogWrite(LED_PIN, i);
delay(10);
}
for (int i = 255; i >= 0; i--) {
analogWrite(LED_PIN, i);
delay(10);
}
}
void running() {
// LED 跑马灯,每隔 200 毫秒依次亮两个 LED
digitalWrite(LED_PIN, HIGH);
delay(200);
digitalWrite(LED_PIN, LOW);
delay(200);
digitalWrite(LED_PIN, HIGH);
delay(200);
digitalWrite(LED_PIN, LOW);
delay(200);
}
```
在这个示例代码中,我们使用 `digitalRead` 函数来检测三个按钮的状态,如果检测到按钮被按下,则改变状态。每个状态对应一个函数,分别实现了 LED 流水灯、呼吸灯和跑马灯的效果。你可以根据需要调整每个状态的实现方式和时间间隔。
阅读全文