我正在使用rbg LED创建可自定义颜色的Arduino照明项目。我正在使用IRremote库来更改LED的“模式”。
这是我的程序:
#include <IRremote.h>
const int RECV_PIN = 7;
IRrecv irrecv(RECV_PIN);
decode_results results;
int redpin = 9;
int greenpin = 10;
int bluepin = 5;
void setup(){
Serial.begin(9600);
irrecv.enableIRIn();
irrecv.blink13(true);
pinMode(redpin, OUTPUT);
pinMode(greenpin, OUTPUT);
pinMode(bluepin, OUTPUT);
}
void loop(){
if (irrecv.decode(&results)){
Serial.println("Before it checks for signal");
if (results.value == 0xFFE21D) { //'TITLE' button
Serial.println("'TITLE' signal detected, before fade starts");
//Fades through colors
int i;
//green to red
for (i = 0; i < 255; i++) {
analogWrite(redpin, i);
analogWrite(greenpin, 255 - i);
analogWrite(bluepin, 0);
delay(1);
Serial.println("Green to red");
}
//red to blue
for (i = 0; i < 255; i++) {
analogWrite(redpin, 255 - i);
analogWrite(greenpin, 0);
analogWrite(bluepin, i);
delay(1);
Serial.println("Red to blue");
}
//blue to green
for (i = 0; i < 255; i++) {
analogWrite(redpin, 0);
analogWrite(greenpin, i);
analogWrite(bluepin, 255 - i);
delay(1);
Serial.println("Blue to green");
}
}
if (results.value == 0xFFD22D) { //'MENU' button
Serial.println("'MENU' button detected");
//LED red
analogWrite(redpin, 255);
analogWrite(greenpin, 0);
analogWrite(bluepin, 0);
}
if (results.value == 0xFF52AD) { //'ON/OFF' button
Serial.println("'STOP' button detected");
//Stops
analogWrite(redpin, 0);
analogWrite(greenpin, 0);
analogWrite(bluepin, 0);
Serial.println("After LED stops");
}
Serial.println("After program");
irrecv.resume();
}
}
在void loop()
内,我有三个if()
语句。第一个检查遥控器上是否按下了某个按钮,LED从绿色变为红色,再由蓝色变为绿色(这仅执行一次,但这对另一个线程来说是个问题)。
第二条if()
语句检查是否有其他按钮按下,并且LED变为红色。我计划将其中几种用于不同的颜色。
第三条if()
语句检查ON / OFF按钮并关闭LED。
我可以在这些之间切换。 问题在于,一旦第一个if()
语句执行并且LED消失,我将无法切换到其他任何一条语句,直到结束为止。
我知道一旦执行了第一条语句,它就不会检查信号,直到完成为止,但是我想不出一种方法来处理它。任何帮助表示赞赏!
答案 0 :(得分:3)
似乎您正在尝试实现一个简单的状态机。为此,您需要切换循环/ if语句。用伪代码:
xyzabc
答案 1 :(得分:3)
Tstenner的状态机是一种解决方法。我将在下面概述另一个内容,但是基本思想是,您需要逐步执行循环操作,以使LED逐步淡入/淡出。这是我的常规方法:
int pins[3] = { redpin, greenpin, bluepin };
int current[3] = { 0, 0, 0 };
int target[3] = { 0, 0, 0 };
led_tick() {
for (int i = 0; i < 3; i += 1) {
if (current[i] == target[i]) continue;
if (current[i] < target[i]) {
current[i] += 1;
} else {
current[i] -= 1;
}
analogWrite(pins[i], current[i]);
}
}
loop() {
// handle buttons, change target values
led_tick();
delay(1); // making this non-blocking would be even better
}
答案 2 :(得分:1)
您可以尝试手工制作的非阻塞
for
delay
millis()
与句点一起使用#define DELAY 5000
int step;
void greenToRed() {
// Non blocking, only check if the waiting period passed
if(changeToRed && millis() > time_1 + DELAY){
// Update the time
time_1 = millis();
// Update the step
step -= 1;
analogWrite(redpin, 255 - step);
analogWrite(greenpin, step);
analogWrite(bluepin, 0);
Serial.println("Green to red");
// Finish condition
if(step =< 0) {
changeToRed = 0;
}
}
}
void loop() {
if (results.value == 0xFFE21D) {
changeToRed = 1;
step = 255;
}
greenToRed();
}