Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

Convert color name string to rgb value in Arduino

I'm doing a project with Arduino ESP8266-1 and a RGB LED strip. The ESP sends strings to the Arduino via serial with the name of the colors to be set (example: "red", "yellow", "purple") and I need to convert that string into an RGB value (eg. (255, 100, 255)).

How can I do this?

I've tried to create a list of array with values like this:

int red = {255, 0, 0};

and next in the loop:

String com = "red";
if (com == "red") {
  colorLed = red;
}

but with more colors, it's not the best way. What would be a better way?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In my opinion the best approach to your problem would be to convert from HEX to RGB (there are quite plenty of C++ samples of code to do that).

You could declare each "color" as their HEX equivalent and use some easy byte converter to convert them to RGB.

Here for example a sample HEX to RGB converter:

byte red, green, blue;
unsigned long rgb = B787B7;

red = rgb >> 16

green = (rgb & 0x00ff00) >> 8;

blue = (rgb & 0x0000ff);

rgb = 0;

rgb |= red << 16;
rgb |= blue << 8;
rgb |= green;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...