Snap! Rainbow LED
Make a tri-color LED fade through the colors of the rainbow
Objective & Learning Goals
- Use variables
- Use loops
- Connect the tri-color LED to port 1.
- (optional) Cover the LED with Styrofoam (or another translucent substance) to diffuse the light.
- Let’s begin with a “when space key pressed” block to launch our program. (It is in the “Control” category.) Drag the block to the middle of the screen.
- To make our program repeat, use a forever loop from the “Control” category.
- We need to keep track of how far along we are in the fading process as we fade the LED from one color to another. A variable will allow our program to do this. Click the “Variables” category and click “Make a Variable”.
- Name the variable “Count”.
- The count variable will start at 0 and increase as the LED fades. Add a “set variable to 0” block to the loop to do this. Then select “Count” from the drop down list.
- Add a repeat loop (from the “Control” category) under the set block and make it repeat 100 times.
- To know how many times the loop has repeated, add a “change Count by 1” block (from the “Variables” category) inside the repeat loop.
- Now we are ready to add a tri-color LED block from the “Looks” category. Place it above the “change Count by 1” block.
We will start by fading from red to green. This means fading green on while fading red off.
- To fade the green LED on, the green part of the tri-color LED should start at 0 and increase to 100. This can be achieved by dragging a “Count” block (from the “Variables” category) into the tri-color LED block’s green section.
- Now to make the red LED fade off, set the red component to 100 minus the current value of the Count variable. Use a “-” block from the “Operators” category to do this.
- To go from green to blue, duplicate the set and repeat blocks.
- Rearrange the blocks to make the green fade out while the blue fades in. Set red to 0.
- Now do the same to fade from blue back to red.
- Press the space bar and the LED will fade through the spectrum!