Go Down

Topic: Typo found on http://arduino.cc/en/Tutorial/Fade (Read 655 times) previous topic - next topic


I was scaling up the original Fade example to four LEDs, having the second fade only after the first made a complete cycle, like an odometer.  There are several things that had me pulling my hair out until I decided to get silly and output my variables to the serial monitor to SEE what the values were doing.  I found a typographical error in the article where it explains:

If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed to its negative. In other words, if fadeAmount is 5, then it is set to -5. If it's 55, then it's set to 5. The next time through the loop, this change causes brightness to change direction as well.

"If it's 55..." should read "If it's -5..."

The next thing got me because of something I did, but perhaps the logic gap should be pointed out.   I commented out the original line in the code that incremented the brightness by the fade amount BEFORE the IF statement.   I did this to allow me to control which LED got brightened/dimmed.  The first LED would fade, but slower than I expected, and the other three never did anything.

Not until after kicking the values of my variables out to the Serial monitor did I learn that since the initial value of the brightness variable tested true by the IF statement it inverted the fade amount like it was programmed to do.  On the next pass of the loop, fadeAmount modified brightness to -5.  -5 being outside the range of the IF statements test, fadeAmount remained -5.  This allowed the routine to continue to run until it the int numerical inversion point (-32678), but due to the math when it was counting down from rolling through to the high positive side, it would not equal '255' at any time on that pass, it would continue to decrease into the negatives and back through again.

This is best avoided if the initial value of the tested variable is set inside the range to be tested for.  Incidentally the page on fading http://arduino.cc/en/Tutorial/Fading offers a slicker way of doing the same thing but with the same risk of starting a variable at a value to be tested for.

suggested modified code below:


This example shows how to fade an LED on pin 9
using the analogWrite() function.

This example code is in the public domain.

int brightness = 5;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

void setup()  {
  // declare pin 9 to be an output:
  pinMode(9, OUTPUT);

void loop()  {
  // set the brightness of pin 9:
  analogWrite(9, brightness);   

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  // wait for 30 milliseconds to see the dimming effect   

Go Up