- MicroPython Cookbook
- Marwan Alsabbagh
- 286字
- 2021-06-24 14:28:07
How to do it...
To do this, perform the following steps:
- Run the following lines of code in the REPL:
>>> from adafruit_circuitplayground.express import cpx >>> import time
- The following block of code defines a list of color values that have the same values and sequence as that which appears in a rainbow:
>>> RAINBOW = [ ... 0xFF0000, # red ... 0xFFA500, # orange ... 0xFFFF00, # yellow ... 0x00FF00, # green ... 0x0000FF, # blue ... 0x4b0082, # indigo ... 0xEE82EE, # violet ... ] >>>
- Then, set a more comfortable level of brightness and turn off all the pixels before starting the animation:
>>> cpx.pixels.brightness = 0.10 >>> cpx.pixels.fill(0x000000) >>>
- Using the following block of code, loop through the seven colors in the rainbow and set one pixel to each color, with a brief delay of 0.2 seconds between each light change:
>>> for i, color in enumerate(RAINBOW): ... cpx.pixels[i] = color ... time.sleep(0.2) ... ... ... >>>
- Use the following animation to go back to each pixel and turn it off at the same rate of 0.2 seconds per light change:
>>> for i in range(len(RAINBOW)): ... cpx.pixels[i] = 0x000000 ... time.sleep(0.2) ... ... ... >>>
- The following code combines all the steps described and wraps these into one infinite while loop. Add this section of code to the main.py file, and then create a continuous rainbow animation:
from adafruit_circuitplayground.express import cpx import time RAINBOW = [ 0xFF0000, # red
0xFFA500, # orange
0xFFFF00, # yellow
0x00FF00, # green
0x0000FF, # blue
0x4b0082, # indigo
0xEE82EE, # violet ] cpx.pixels.brightness = 0.10 cpx.pixels.fill(0x000000) while True: for i, color in enumerate(RAINBOW): cpx.pixels[i] = color time.sleep(0.2) for i in range(len(RAINBOW)): cpx.pixels[i] = 0x000000 time.sleep(0.2)