控制 RGB LED 开/关 - 比使用"if"更智能的方式?(C++年阿杜伊诺)



我想控制三个RGB LED的颜色(总共9个LED(以及打开还是关闭。我正在使用带有PlatformIO和FastLED库的Arduino,使用FastLED.show((打开它们

我的显示器上有六个按钮LED1LED 2发光二极管3

按下并时为真

错误发布时

void bt0PopCallback(void *ptr){uint32_t dual_state; NexDSButton *btn = (NexDSButton *)ptr; bt0.getValue(&dual_state); if(dual_state){ LED1 = true; } else{ LED1 = false; } }
void bt1PopCallback(void *ptr){uint32_t dual_state; NexDSButton *btn = (NexDSButton *)ptr; bt1.getValue(&dual_state); if(dual_state){ LED2 = true; } else{ LED2 = false; } }
void bt2PopCallback(void *ptr){uint32_t dual_state; NexDSButton *btn = (NexDSButton *)ptr; bt2.getValue(&dual_state); if(dual_state){ LED3 = true; } else{ LED3 = false; } }

例如:按下LED1按钮时,LED1=true;松开按钮时,LED1=false

如果LED1=true且RED=true,则该led将变为红色。当释放红色并按下绿色时,LED1现在变为绿色。如果释放LED1并按下LED2,则LED1熄灭,LED2变为绿色。

我想出了一个:

if(BLUE == true){BLUEV = 255;} else { BLUEV = 0;}
if(RED == true){REDV = 255;} else { REDV = 0;}
if(GREEN == true){GREENV = 255;} else { GREENV = 0;}
if(LED1 == true){leds[0] = CRGB(REDV, GREENV, BLUEV); } else { leds[0] = CRGB(0, 0, 0); }
if(LED2 == true){leds[1] = CRGB(REDV, GREENV, BLUEV); } else { leds[1] = CRGB(0, 0, 0); }
if(LED3 == true){leds[2] = CRGB(REDV, GREENV, BLUEV); } else { leds[2] = CRGB(0, 0, 0); }
FastLED.show();

但我认为这显然是不完美的。

有人建议如何更好地编码它吗?也许用开关盒?

干杯!

对于初学者,您可以在回调中不使用if-else的情况下将dual_state分配给相应的LED。

这里有一个例子:

void bt0PopCallback( void* ptr )
{
uint32_t dual_state;
NexDSButton* btn = (NexDSButton*) ptr;
bt0.getValue( &dual_state );
LED1 = dual_state;                          // direct assignment
}

对于颜色代码中的其他if-else变体,可以使用三元运算符?:来清理如下内容:

BLUEV  = BLUE  ? 255 : 0;
REDV   = RED   ? 255 : 0;
GREENV = GREEN ? 255 : 0;

并且,要设置leds数组的值,请使用for循环。LED1LED2LED3可以使用要在循环中用于leds的对应值的std::array来分组。

以下是std::array:的示例

#include <array>
const std::array<decltype(LED1), NUM_LEDS> LED { LED1, LED2, LED3 };
for ( int i = 0; i < NUM_LEDS; ++i )            // loop to set the colors of LEDs
{
leds[i] = LED[i] ? CRGB(REDV, GREENV, BLUEV) : CRGB(0, 0, 0);
}

NUM_LEDS表示leds阵列的大小,即:

#define NUM_LEADS 3
CRGB leds[NUM_LEADS];

最新更新