Arduino代码中有太多重复代码

时间:2018-10-27 11:04:04

标签: arduino serial-port rgb

在Arduino上制作策划游戏时遇到问题。 我有4个RGB LED,每个LED都有各自的引脚名称(red1,green1,blue1,red2,green2,blue2等)。

现在我的问题是,当我输入4种颜色与Arduino在游戏开始时选择的颜色进行比较时。代码太重复了,而且由于我仍然在学习Arduino,所以我想知道是否有解决方案。

这是我的代码部分,用于为具有所选颜色的LED分配颜色(颜色代码1 =绿色,2 =红色等)

    void Convertmycolor()
{
  if (colorpicker1 == 1)
  {
    red1 = 0;
    green1 = 255;
    blue1 = 255;

  }
  else if (colorpicker1 == 2)
  {

    red1 = 0;
    green1 = 0;
    blue1 = 255;
  }
  else if (colorpicker1 == 3)
  {

    red1 = 255;
    green1 = 255;
    blue1 = 0;
  }
  else if (colorpicker1 == 4)
  {
    red1 = 255;
    green1 = 0;
    blue1 = 0;
  }
  else if (colorpicker1 == 5)
  {

    red1 = 255;
    green1 = 255;
    blue1 = 255;
  }










  if (colorpicker2 == 1)
  {
    red2 = 0;
    green2 = 255;
    blue2 = 255;

  }
  else if (colorpicker2 == 2)
  {

    red2 = 0;
    green2 = 0;
    blue2 = 255;
  }
  else if (colorpicker2 == 3)
  {

    red2 = 255;
    green2 = 255;
    blue2 = 0;
  }
  else if (colorpicker2 == 4)
  {
    red2 = 255;
    green2 = 0;
    blue2 = 0;
  }
  else if (colorpicker2 == 5)
  {

    red2 = 255;
    green2 = 255;
    blue2 = 255;
  }











  if (colorpicker3 == 1)
  {
    red3 = 0;
    green3 = 255;
    blue3 = 255;

  }
  else if (colorpicker3 == 2)
  {

    red3 = 0;
    green3 = 0;
    blue3 = 255;
  }
  else if (colorpicker3 == 3)
  {

    red3 = 255;
    green3 = 255;
    blue3 = 0;
  }
  else if (colorpicker3 == 4)
  {
    red3 = 255;
    green3 = 0;
    blue3 = 0;
  }
  else if (colorpicker3 == 5)
  {

    red3 = 255;
    green3 = 255;
    blue3 = 255;
  }








  if (colorpicker4 == 1)
  {
    red4 = 0;
    green4 = 255;
    blue4 = 255;

  }
  else if (colorpicker4 == 2)
  {

    red4 = 0;
    green4 = 0;
    blue4 = 255;
  }
  else if (colorpicker4 == 3)
  {

    red4 = 255;
    green4 = 255;
    blue4 = 0;
  }
  else if (colorpicker4 == 4)
  {
    red4 = 255;
    green4 = 0;
    blue4 = 0;
  }
  else if (colorpicker4 == 5)
  {

    red4 = 255;
    green4 = 255;
    blue4 = 255;
  }
}

如您所见,它非常重复,我希望它更短一些。我尝试使用Google谷歌搜索,但在这种情况下(或搜索不佳)没有发现任何可以帮助我的东西

希望您能帮助我。 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用数组索引来映射您的值,例如:

#define COLOR_LENGTH 4
#define PICKER_LENGTH 4

struct Color {
    uint8_t r, g, b;
};

const Color colorTable[] = {
    {0, 255, 255},
    {0, 0, 255},
    {255, 255, 0},
    {255, 0, 0},
    {255, 255, 255}
};

uint8_t colorPickers[PICKER_LENGTH];
Color colors[COLOR_LENGTH];

转换只是将颜色映射到正确的索引:

//set the pickers
colorPickers[0] = 3;
colorPickers[1] = 1;
colorPickers[2] = 4;
colorPickers[3] = 5;
//set colors according to table
for (uint8_t i = 0; i < COLOR_LENGTH; i++) {
    colors[i] = colorTable[colorPickers[i] - 1];
}