Print

Snap! Rainbow LED

Make a tri-color LED fade through the colors of the rainbow

Programming Language

Snap!

Subjects

Programming Tutorials

Grades

4-5, 6-8

Free Teacher Materials

Get Access

Objective & Learning Goals

  • Use variables
  • Use loops

Hummingbird setup

  1. Connect the tri-color LED to port 1.
  2. (optional) Cover the LED with Styrofoam (or another translucent substance) to diffuse the light.

Programming steps

  1. 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.
  2. To make our program repeat, use a forever loop from the “Control” category.
  3. 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”.
  4. Name the variable “Count”.
  5. 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.
  6. Add a repeat loop (from the “Control” category) under the set block and make it repeat 100 times.
  7. To know how many times the loop has repeated, add a “change Count by 1” block (from the “Variables” category) inside the repeat loop.
  8. 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.
  9. 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.
  10. 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.
  11. To go from green to blue, duplicate the set and repeat blocks.
  12. Rearrange the blocks to make the green fade out while the blue fades in. Set red to 0.
  13. Now do the same to fade from blue back to red.
  14. Press the space bar and the LED will fade through the spectrum!