【发布时间】:2021-05-04 04:55:57
【问题描述】:
我正在进行串行通信并尝试制作 led 淡入淡出效果, 这是我的 LED 功能,它面临延迟问题,显然是 for 循环。任何人都可以提出更好的逻辑或解决方案来解决这个问题而不会在 LED 中获得延迟?
void loop() {
// serial communication
while(Serial.available() > 0 ){
int inByte = Serial.read();
Serial.print(inByte);
if (inByte > 0) {
// if byte is 255, then the next 3 bytes will be new rgb value
if (inByte == 255) {
setColors = true;
colorSetCounter = 0;
} else if (setColors) {
switch (colorSetCounter) {
case 0:
redVal = inByte;
break;
case 1:
greenVal = inByte;
break;
case 2:
blueVal = inByte;
setColors = false;
receiveNotes = true;
fill_solid(leds, NUM_LEDS, CRGB::Black);
FastLED.show();
break;
}
colorSetCounter++;
} else if (receiveNotes) {
controlLeds(inByte);
}
}
}
}
void controlLeds (int note) {
note -= 1;
if (!leds[note]) {
leds[note].red = redVal;
leds[note].green = greenVal;
leds[note].blue = blueVal;
}
else {
for(int i =0; i<=255; i++){
leds[note].fadeToBlackBy(i);
FastLED.show();
if(!leds[note]){
break;
}
}
}
FastLED.show();
}
【问题讨论】:
-
如果我没记错的话,Arduino的主程序是循环运行的。 (我强烈认为这是有原因的。)因此,您可能需要创建一个更新函数来增加或减少 LED 的强度,而不是为 LED 衰减创建一个嵌套循环。这个变量必须得到一个整体的生命周期——也许,一个全局变量是有意义的(是的,尽管全局变量通常被认为是不好的风格)。此外,可能有必要涉及延迟,例如通过存储上次更新的时间并在下次更新之前检查是否已经过了一段时间。
-
您能详细说明“延迟问题”吗?
-
@Piglet 是的,当同时发生关闭事件时,每个音符都会导致延迟,例如,如果我有 4 个音符打开然后关闭,则循环将一个一个地淡化所有事件,阻止其他事件。
-
.fadeToBlackBy(i)到底是做什么的?您还提到了串行端口,但我在您的代码中没有看到对串行端口的引用。 -
@lurker 刚刚更新了代码,有空看看 :)
标签: c++ arduino serial-port arduino-uno fastled