Fading LED Experiments

After completing the Fading LED project, test yourself by trying these experiments.

1 Instead of manually changing the fade value, the for loop command can be used to automatically change the fade value.

In the sample code, the for loop is used to automatically change the fadeValue variable from 0 to 255 in increments of 1.


Three things are specified inside the for command:
  1. The starting value for the counting variable. In this case, declaring and assigning 0 to fadeValue using the = assignment command.
  2. The < conditional test to end the for loop. In this case, testing whether fadeValue is < 256. The loop repeats as long as this condition is true, and terminates when this condition is false.
  3. Each time round the loop the counting variable is incremented by 1. This is specified by the incrementer operator ++ for the fadeValue variable.
The body of the for loop is bracketed by the two braces { and }. All of the commands inside the loop body (in this case, the analogWrite and delay statements) are executed repeatedly as long as the condition in the for loop is true. Initially the counting variable fadeValue is assigned the value 0. At the end of the loop, fadeValue is incremented by one and is tested to see if the condition is still true or not. If the condition is true, then the loop is repeated, otherwise, the loop is terminated.
Fade LED
2 To make the LED fade in and out, we use two for loops in the void loop() routine.
















The first for loop causes the LED to fade in by counting from 0 up to 255.





The second for loop causes the LED to fade out by counting from 255 down to 0. Notice the ending conditional test greater than or equal to >= is used, and the decrementer operator – – (two hypens) for decrementing the counting variable fadeValue by one.
Fade LED
3 Connect two LEDs and make both of them fade in and out together at the same time.
4 Connect two LEDs and make one of them fade in while the second one fade out.
for (int fadeValue=0; fadeValue<256; fadeValue++) {
   analogWrite(led_one, fadeValue);       // first LED fade in
   analogWrite(led_two, 255-fadeValue);   // second LED fade out
}