1

我已经在 Arduino 中编写了循环通过 3 个 LED 彩色灯的代码,但它似乎(代码)容易出错,所以我试图想出一种新的方法来编写它。由于复杂性,我将坚持使用我正在尝试做的 phesdo 代码。这里是:

If (red LED isn't max and green LED is 0 and blue LED is 0)
  {inc red LED; update dot matrix}
If (red LED is max and green LED isn't max and blue LED is 0)
  {inc green LED; update dot matrix}
If ((red LED is/has-been max but not 0 ) and green LED is max and blue LED is 0)
  {dec red; update dot matrix}
If (red LED is 0 and green LED is max and blue LED isn't max)
  {inc blue; update dot matrix}
If (red LED is 0 and (green LED is/has-been max but not 0) and blue LED is max)
  {dec green; update dot matrix}
If (red LED isn't Max and green LED is 0 and blue is Max )
  {inc red; update dot matrix}
If (red LED is Max and green LED is 0 and (blue LED is/has-been Max but not 0))
  {dec blue; update dot matrix}

Update LED Driver;

注意:对于视觉来说,它是一个红色->橙色->绿色->蓝绿色->蓝色->粉色->重复的色轮

需要注意的是,所有这些都在一个循环中,在退出以获取其他数据之前只运行一次。然后它必须返回到这个循环并记住它离开的颜色位置。否则,将所有这些包装在 for 循环中并线性执行它会很容易。因为它必须增​​加或减少一种颜色,如果您愿意,请了解它的颜色位置,更新 LED 驱动程序,然后返回增加或减少记住它停止的位置。那么有没有人有更好的代码方法,伪风格,除了这种复杂的 if 语句风格,我还可以使用。

4

3 回答 3

2

通过简单的情况图,您可以找到一个公式,该公式根据您在每个刻度上递增的全局计数器将强度直接应用于单个组件,代码如下(我刚刚编写并没有经过测试,但应该足以让您了解它是如何工作的):

int counter = 0; // counter you should increment on each tick
int phases = 6; // total phases in a cycles
int cycleLength = max_steps * phases; // total ticks in a cycle

int currentStepOfCycle = counter % cycleLength;
int currentPhase = currentStepOfCycle / max_steps;
int currentStepOfPhase = currentStepOfCycle % max_steps;

// this is how much phase shifts are performed for each primary color to have the raising line in phase 0
int phase_shifts[3] = {2, 0, 4}; 

// for each color component
for (int i = 0; i < 3; ++i) {
  // shift the phase so that you have / at phase 0
  int shiftedPhase = (currentPhase+phase_shifts[i])%phases;

  if (shiftedPhase == 1 || shiftedPhase == 2)
    intensity[i] = MAX;
  else if (shiftedPhase == 0)
    intensity[i] = currentStepOfPhase;
  else if (shiftedPhase == 3)
    intensity[i] = MAX - currentStepOfPhase;
  else
    intensity[i] = 0;
}

思路由此而来:

在此处输入图像描述

需要进行这种转变,因为通过为不同颜色分量添加当前相位的增量,可以始终考虑相位 0、1、2 和 3,以了解每个分量的强度应该提高、下降或设置为最大值。

这应该适用于您想要轻松应用的任何强度步骤。

于 2013-04-26T18:19:33.027 回答
2

至少在我阅读您的if陈述时,您有 7 个不同的状态(也许应该是 8 个?),当您到达最后一个状态时,它会回到第一个状态。

这很容易实现为带有小型查找表的计数器,以将状态编号映射到应该为某个状态点亮的 LED。

于 2013-04-26T18:02:12.350 回答
2

是的,这不是很好......我会做类似的事情......

typedef struct{ //maybe stick this in a union, depending on what the compiler does to it.
    unsigned char r:2;
    unsigned char g:2;
    unsigned char b:2;
}color;
const int numOfColors = 3;
color colors[numOfColors] = {
    {2,0,0},//r
    {1,1,0},//o
    {0,2,0}//g
};

for(int i = 0 ; 1 ; i++)
{
    color c = colors[i%numOfColors];
    //set color
    //update
    //wait
}
于 2013-04-26T18:01:46.840 回答