Looping over hardware

In this chapter we learn about looping using hardware (simulation).

One NeoPixel at a time

_images/oneneoatatime.gif

The cpx.pixels can be accessed by index numbers, from 0 to 9. This way, we can turn on one NeoPixel at a time.

 1# import CPX library
 2from adafruit_circuitplayground.express import cpx
 3import time
 4
 5BLUE = (0, 0, 255)
 6
 7i = 0
 8
 9while True:
10    # start your code here
11    if i == 10:
12        time.sleep(10)
13        continue
14    cpx.pixels[i] = BLUE
15    i += 1
16    time.sleep(0.5)

On line number 7, we declared a variable which selects the correct NeoPixel, and then on line number 14 we are turning on that NeoPixel to Blue color, and then increasing the variable to go to the next NeoPixel. The conditional if statement on line 11 makes sure that when we turn on all the lights, we sleep for 10 seconds and continue to do so.

First Red and then Blue

_images/redthenblue.gif

Here using two for loops, we are first turning on each NeoPixel in Red and then in Blue.

 1# import CPX library
 2from adafruit_circuitplayground.express import cpx
 3import time
 4
 5RED = (255, 0, 0)
 6BLUE = (0, 0, 255)
 7
 8while True:
 9    for i in range(0, 10):
10        cpx.pixels[i] = RED
11        time.sleep(0.5)
12
13    time.sleep(0.5)
14
15    for i in range(0, 10):
16        cpx.pixels[i] = BLUE
17        time.sleep(0.5)