在Arduino中创造更好的循环

时间:2013-04-26 17:53:53

标签: c++ c loops arduino

我在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驱动程序,然后回到inc或dec记住它停止的位置。所以,除了这种复杂的if语句风格之外,还有任何人有更好的代码方法,伪风格。

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:2)

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

这很容易实现为一个带有小查找表的计数器,用于映射状态编号,LED应该为状态点亮。

答案 2 :(得分: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;
}

这个想法是这样的:

enter image description here

需要进行移位,因为通过为不同颜色分量的当前相位添加增量,可以始终考虑阶段0,1,2和3以了解强度应该是每次增加,下降或设置为最大值成分

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