【问题标题】:Convert color name string to rgb value in Arduino在 Arduino 中将颜色名称字符串转换为 rgb 值
【发布时间】:2021-01-12 11:20:17
【问题描述】:

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

我该怎么做?

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

int red = {255, 0, 0};

循环中的下一个:

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

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

【问题讨论】:

  • 发送颜色名称而不是 rgb touple 有什么好的理由吗?
  • 因为 esp 已连接到谷歌助手,谷歌在我的命令中向我发送字符串,如:"{"deviceId":"xxx","action":"action.devices.commands.ColorAbsolute", "值":{"颜色":蓝色}}"

标签: arduino rgb lookup-tables arduino-c++


【解决方案1】:

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

您可以将每个 "color" 声明为它们的 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;

【讨论】:

  • 它是 0xB787B7 而不是 B787B7 ,你不要回答这个问题。我也了解您建议通过串行连接发送该 rgb 值,然后将其拆分为 r、g 和 b。如果您可以简单地发送 3 r g b 字节,为什么还要发送 4 字节数字?这对我来说毫无意义。
【解决方案2】:

我认为发送字符串表示而不是 rgb touples 并不聪明,但如果你坚持这样做,你可以使用哈希映射。

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

【讨论】:

    猜你喜欢
    • 2017-06-24
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 2012-11-01
    • 2012-10-13
    • 2013-12-10
    • 2012-03-30
    • 2017-09-11
    相关资源
    最近更新 更多