TheBestPlayer
TheBestPlayer

Reputation: 404

ENUM and array declaration using enum to create an array of objects

I am writing a wrapper for neopixel library. I am adding a full source code of my program:

I have created my own custom function toggle_led_strip which is using a function from the neopixelbus led strip library.

#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:
}

Normally, when I want to create a colour variable, I must create it in such way:

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

However, I am learning about different ways of creating colour objects and someone has suggested me to use ENUM and array method as such:

enum COLORS
{
blue,black
};

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

From what I understand, the code above will set the first variable of enum (blue) to the {0,0,255} and the second variable of enum (black) to {0} so the result should be exactly the same as if I have used

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

is that correct understanding?

Then I try to pass the color to the function as following:

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

But it does not work when using enum and array method and works perfectly with the first method

Upvotes: 0

Views: 735

Answers (1)

TheBestPlayer
TheBestPlayer

Reputation: 404

Those who are interested in the solution:

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);
}

It turned out to be quite simple once you understand that an ENUM is treated as an array index and nothing else. It works as expected now.

Upvotes: 0

Related Questions