【问题标题】:ENUM and array declaration using enum to create an array of objectsENUM 和数组声明使用枚举创建对象数组
【发布时间】:2021-09-19 11:45:31
【问题描述】:

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

我创建了自己的自定义函数 toggle_led_strip,它使用了 neopixelbus led 条库中的​​函数。

#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,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,0,255);
RgbColor black(0);

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

enum COLORS
{
blue,black
};

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

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

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

这样理解正确吗?

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

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

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

【问题讨论】:

  • 请注意,arduino 代码不是 C。RgbColor blue(0,0,255); 例如不是有效的 C。有一个 arduino-C++ 标签可供您使用。
  • 你的代码真的是 C 语言吗?对我来说它看起来像 C++。
  • 我在 Arduino IDE 上编程。正如kaylum建议的那样,代码是arduino c++。我添加了一个新标签。感谢发现

标签: arrays enums arduino-c++ neopixel


【解决方案1】:

对解决方案感兴趣的人:

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 被视为数组索引而不是其他任何东西,事实证明这非常简单。它现在按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 2015-02-23
    相关资源
    最近更新 更多