Auto LED Fader

In this program, you use two for loops to repeat the analogWrite() statement over and over again, giving an LED a smooth fade from dim to bright to dim. 

Code

/* * Fade an LED's brightness up and down using 'for' loops and analogWrite() * The analogWrite() command works only on pins 3,5,6,9,10,11 */ void setup() { pinMode(5, OUTPUT); //LED } void loop() { //create a brightness var starting at 0 and increase it by 1 up to 255 for (int brightness = 0; brightness < 256; brightness++) { analogWrite(5, brightness); //each loop of the 'for' loop write the brightness value delay(5);//time between updating and writing the brightness variable } //create a new brightness variable starting at 255 decrease it by 1 to 0 for (int brightness = 255; brightness >= 0; brightness--) { analogWrite(5, brightness); delay(5); } } // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Challenges

How many can you complete? Change the code and hardware according to the challenges below. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!

Videos

Read the Code Walkthrough Text (click to open)

Concepts

No new concept here- observe how the for loop can work with different components! 

Quiz

If you're having trouble, try to run a program that can help you find the answer.

1. Which code commands can you use inside the curly braces of a 'for' loop?




2. True or False:
When you create a variable inside a 'for' loop, it only exists inside that 'for' loop.