0

我正在尝试在 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] ; 
       }     
     }                         
   }
 }

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

知道有什么问题吗?

4

1 回答 1

0

我想到了。看起来我忘记了一行代码。

  previousMillis[counter] = currentMillis;

我应该把它放在代码中的第一个 if 语句中。我猜想通过使用串行打印进行观察的行为会减慢速度,以至于代码似乎可以正常工作。

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

于 2012-11-27T21:07:58.703 回答