## Step 1 - Build the Project

Topics Covered:

In this piece of code, you combine a function, nested loops, and random numbers to create a multicolor LED fade lamp. The code as a whole is dense, but each part breaks down into reasonable chunks.

## Step 2 - Upload the Code

 12 14 18 24 30
/* * Fade random colors from bright to dim by changing the flicker rate */ void setup() { pinMode(4, OUTPUT); //LED pins to fade pinMode(5, OUTPUT); pinMode(6, OUTPUT); } //create a function that takes in 4 values from loop and digitalWrites them void fade(int _on4, int _on5, int _on6, int _offTime) { for (int repeat =0; repeat <(40 /_offTime); repeat++) { digitalWrite(4,_on4); digitalWrite(5,_on5); digitalWrite(6,_on6); delay(1); digitalWrite(4,LOW); digitalWrite(5,LOW); digitalWrite(6,LOW); delay(_offTime); } } void loop() { // Set each LED on or off at random byte on4 = random(2);//will return either a 1 or a 0 byte on5 = random(2); byte on6 = random(2); // if all 3 randoms are zero, all lights are off. Default to one on. if ( (on4 + on5 + on6) == 0) { on4 = 1; } for (byte offTime =20; offTime >0; offTime--) { // fade from dim to bright fade(on4,on5,on6, offTime); } for (byte offTime =0; offTime <20; offTime++) { //fade from bright to dim fade(on4,on5,on6, offTime); } } //Try changing the "40/ _offTime" to "20/ _offTime" to change fade speed // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense

## Step 3 - Read the Walkthrough

First, you set up the hardware that you’re using so Maker Board can send higher voltage to the output pins. Here you use pins 4, 5, and 6.

Next is the creation of a function named fade. The idea behind the function is that it clusters often-used code together and makes it easy to access. When you call the function, you say “Function, do your cluster of code.” The function runs like a separate loop.

In this code, the function takes care of the flickering action for all three pins. You pass the function the values of on4,on5,on6,offTime (the four arguments for the function) and the function uses those inputs to flicker the lights.

The loop() section of the code is handling the assignment of the variables on4, on5, on6, and offTime and controlling the direction of the fade i.e. “When should the fade be getting brighter?” “When should it be getting dimmer?”.

The function and the loop are communicating very quickly. For each cycle of fading (dim to bright to dim), the loop has sent the function 40 values for each LED color. If the LED is on, the loop sends a ‘1’ to the function 20 times to fade it up, then sends a ‘1’ to the function 20 times to fade it down.