Multi-Color Glow Lamp
 

Step 1 - Build the Project

In this code, two variables are interacting with each other, then passing a value to the outputs. The variables in the code are the only inputs here.

Step 2 - Upload the Code

/* * Fade multicolor LED colors on pins 9,10, and 11 using analogWrite(). * The analogWrite() function works on digital pins 3,5,6,9,10,11. */ int brightness = 0; int fade = 3; //The size of the 'steps' our fade will take during each loop void setup(){ //LED pins pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); } void loop(){ //Writing the values at different levels makes the fade more random analogWrite(9,brightness); analogWrite(10,brightness+50); analogWrite(11,brightness+100); brightness = brightness + fade; //update brightness each loop //if the brightness is at it's min or max, reverse fade's direction if (brightness == 0 || brightness == 255){ fade = -fade; } delay(100); //Change the dim speed and see what happens! } // Change the initial value of 'fade' and see the effect on your lamp // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

Our idea is to have three colors fading up and down at slightly different strengths for a relaxing glow lamp. To create that steady fade, you create two variables: one holds the brightness, which is changed by ‘fade’ amount each loop through the code.

After setting up each output of the multicolor LED, the loop first gives each LED color a brightness to analogWrite(). To make each color fade a little differently, you can add some random amount from 0 to 255 to the starting point of any color. For the first loop through, the brightnesses will be 0, 50, and 100. On the second loop, the brightness values will equal 3,53, and 103.

When the brightness variable reaches its maximum, the ‘if’ statement changes the fade variable to a negative number, so the fade starts to reverse. Fade is then changed back to a positive when the brightness reaches 0.

There are two easy ways to modify this code to see the effects. First, change the fade variable to something larger so that the steps between each brightness are larger. Next, change the delay in the program to see the effect of making each step last a shorter while.