尝试在多个LED上消除arduino的奇怪问题

时间:2012-11-27 20:59:51

标签: c++ arduino

我正试图在Arduino Uno上测试多个LED上的Fade。这是我写的代码

int led[2] = {9,10};           // the pin that the LED is attached to
int brightness[2] = {0,0};    // how bright the LED is
int fadeAmount[2] = {5,15};    // how many points to fade the LED by
long previousMillis[2] = {0,0};        // will store last time LED was updated

long interval[2] = {30, 50};
// the setup routine runs once when you press reset:
void setup()  { 
  // declare pin 9 to be an output:
   pinMode(led[0], OUTPUT);
   pinMode(led[1], OUTPUT);
   Serial.begin(9600);
 } 

 // the loop routine runs over and over again forever:
 void loop()  { 
   // set the brightness of pins:

   for (int counter = 0; counter < 2; counter++) {
     unsigned long currentMillis = millis();

     analogWrite(led[counter], brightness[counter]);
     Serial.print("LED ");
     Serial.print(led[counter]);
     Serial.print(": Brightness ");
     Serial.println(brightness[counter]);    

     if (currentMillis - previousMillis[counter] > interval[counter]) {
       // change the brightness for next time through the loop:
       brightness[counter] = brightness[counter] + fadeAmount[counter];

       // reverse the direction of the fading at the ends of the fade: 
       if (brightness[counter] == 0 || brightness[counter] == 255) {
         fadeAmount[counter] = -fadeAmount[counter] ; 
       }     
     }                         
   }
 }

这是奇怪的事情。如果我注释掉Serial的东西(打印并开始),则淡入淡出不起作用。他们只是“闪烁”一点。

知道出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

我明白了。看起来我忘记了一行代码。

  previousMillis[counter] = currentMillis;

我应该把它放在代码中的第一个if语句中。我想通过使用串行打印进行观察的行为减慢了速度,使代码看起来有效。

男孩,我觉得自己很愚蠢。