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

问题描述

我正在使用 Arduino ESP8266-1 和 RGB LED 灯条做一个项目。 ESP 通过串行向 Arduino 发送带有要设置的颜色名称的字符串(例如:“红色”、“黄色”、“紫色”),我需要将该字符串转换为 RGB 值(例如(255, 100,255)).

我该怎么做?

我尝试创建一个包含如下值的数组列表:

int red = {255,0};

和循环中的下一个

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

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

解决方法

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

您可以将每个 "color" 声明为其等效的十六进制,并使用一些简单的字节转换器将它们转换为 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 元组并不聪明,但如果您坚持这样做,您可以使用哈希映射。

Example using Wiring

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