使用枚举创建对象数组的枚举和数组声明

问题描述

我正在为 neopixel 库编写包装器。我正在添加我的程序的完整源代码

我创建了自己的自定义函数 toggle_led_strip,它使用了 neopixelbus led strip 库中的一个函数

#include "NeoPixelBus.h"
#include <Adafruit_I2CDevice.h>
#define PixelCount  8 // this example assumes 4 pixels,making it smaller will cause a failure
#define PixelPin  27  // make sure to set this to the correct pin,ignored for Esp8266
#define colorSaturation 250

RgbColor blue(0,255);
RgbColor black(0);

NeoPixelBus<NeoGrbFeature,NeoEsp32Rmt0800KbpsMethod> strip(PixelCount,PixelPin);


void toggle_led_strip(RgbColor colour){
        strip.SetPixelColor(0,colour);
        strip.Show();
        delay(100);
        strip.SetPixelColor(0,black);
        strip.Show();
        delay(100);
}

void setup() {
  strip.Begin();

  // put your setup code here,to run once:

}

void loop() {
  toggle_led_strip(blue);
  // put your main code here,to run repeatedly:
}

通常,当我想创建一个颜色变量时,我必须以这样的方式创建它:

RgbColor blue(0,255);
RgbColor black(0);

但是,我正在学习创建颜色对象的不同方法,有人建议我使用 ENUM 和数组方法

enum COLORS
{
blue,black
};

RgbColor a_color[2] = {
  [blue] = {0,255},[black] ={0}
};

据我了解,上面的代码会将 enum(蓝色)的第一个变量设置为 {0,255},将 enum(黑色)的第二个变量设置为 {0},因此结果应该与如果我用过

RgbColor blue(0,255);
RgbColor black(0);

这是正确的理解吗?

然后我尝试将颜色传递给函数,如下所示:

//void toggle_led_strip(RgbColor colour) This is function prototype
toggle_led_strip(blue)

但在使用枚举和数组方法时不起作用,与第一种方法完美配合

解决方法

对解决方案感兴趣的人:

void toggle_led_strip(COLORS colour){
        strip.SetPixelColor(0,a_color[colour]);
        strip.Show();
        delay(100);
        strip.SetPixelColor(0,a_color[black]);
        strip.Show();
        delay(100);
}

一旦你理解了 ENUM 被视为数组索引而不是其他任何东西,它就会变得非常简单。它现在按预期工作。