将颜色名称字符串转换为Arduino中的rgb值



我正在用Arduino ESP8266-1和RGB LED条做一个项目。ESP通过串行将字符串发送到Arduino,其中包含要设置的颜色的名称(例如:"红色"、"黄色"、"紫色"(,我需要将该字符串转换为RGB值(例如(255100255((。

我该怎么做?

我尝试创建一个数组列表,其中的值如下:

int red = {255, 0, 0};

循环中的下一个:

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

但如果有更多的颜色,这不是最好的方法。有什么更好的方法?

在我看来,解决问题的最佳方法是从HEX转换为RGB(有很多C++代码样本可以做到这一点(。

您可以声明每个"颜色">作为它们的HEX等价物,并使用一些简单的字节转换器将它们转换为RGB。

例如,这里的示例HEX到RGB转换器:

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;

我认为发送字符串表示而不是rgb头是不明智的,但如果你坚持这样做,你可以使用哈希图。

使用布线的示例:

#include <HashMap.h>
//create hashMap that pairs char* to int and can hold 3 pairs
CreateHashMap(hashMap, char*, int, 3); 
void setup()
{
Serial.begin(9600);
//add and store keys and values
hashMap["newKey"] = 12;
hashMap["otherKey"] = 13;
//check if overflow (there should not be any danger yet)
Serial.print("Will the hashMap overflow now [after 2 assigns] ?: ");
Serial.println(hashMap.willOverflow());
hashMap["lastKey"] = 14;
//check if overflow (this should be true, as we have added 3 of 3 pairs)
Serial.print("Will the hashMap overflow now [after 3 assigns] ?: ");
Serial.println(hashMap.willOverflow());
//it will overflow, but this won't affect the code.
hashMap["test"] = 15;
//change the value of newKey
Serial.print("The old value of newKey: ");
Serial.println(hashMap["newKey"]);
hashMap["newKey"]++;
Serial.print("The new value of newKey (after hashMap['newKey']++): ");
Serial.println(hashMap["newKey"]);
//remove a key from the hashMap
hashMap.remove("otherKey");
//this should work as there is now an availabel spot in the hashMap
hashMap["test"] = 15;
printHashMap();
}
void loop() {
}
void printHashMap() 
{
for (int i=0; i<hashMap.size(); i++) 
{
Serial.print("Key: ");
Serial.print(hashMap.keyAt(i));
Serial.print(" Value: ");
Serial.println(hashMap.valueAt(i));
}
}

最新更新