Lesson 2: Lighting Lights

Want to do something over and over again? That's something computers are great at. It can be done in different ways, but we'll start with for loops. The basic for loop:

        for i in range([start], stop, [step]):
      

Hide Notes ▼

The range function can be used in three ways.

1) range(stop)

Given a stopping value only,
  • Starts at 0 by default.
  • Ends at one less than the stopping value
The program:

            for i in range(5):
              print(i)
           
will output:

            0
            1
            2
            3
            4
           

2) range(start, stop)

Given a starting and a stopping value, The program:

            for i in range(2, 6):
              print(i)
           
will output:

            2
            3
            4
            5
           

1) range(start, stop, step)

Given a starting, stopping, and a step value,
  • Without the step value the default step is 1
  • You still end up at one step less than the stopping value.
The program:

            for i in range(4, 10, 2):
              print(i)
           
will output:

            4
            6
            8
           

Example

The test2.py file lights up every other light:

            import board
            import neopixel

            nPix = 20

            pixels = neopixel.NeoPixel(board.D18, nPix)

            for i in range(0, nPix, 2):
            	pixels[i] = (0, 0, 255)
          
Line 8: It uses a for loop with a starting value (0), ending value (nPix), and step value (2). nPix is defined on Line 4 with a value of 20.

Exercises

1) Make the last 5 lights red.
Show Notes ▼
Show Solution ▼
2) Make lights 5 through 10 blue.
3) Light up every other light.
4) Going backwards, make all of the lights light up one at a time (with a 0.25 seconds between each lighting up.)
Show Hint ▼
5) Repeat this sequence 5 times (lighting up all lights backwards with a 0.25 second delay between lights).
Show Notes ▼
Show Solution ▼
6) Over 2.5 seconds have a single light of the 20 light up and march across the strip, with all the other lights being black (you may have done this before in the Lighting Lights exercises).
7) Do the same as above, but backwards. (i.e.: Over 2.5 seconds have a single light of the 20 light up and march across the strip, with all the other lights being black.
8) Have the previous two sequences repeat 5 times so the single light seems to be going back and forth.