Andreas Motzek
Published © CC BY

Complex behaving Hardware with CircuitPython - Part II

Some projects need more than loops and sleeps. See how to use the cooperative_multitasking library with this four part guide.

BeginnerProtip1 hour30
Complex behaving Hardware with CircuitPython - Part II

Things used in this project

Hardware components

Adafruit Neo Trinkey
×1

Software apps and online services

Mu Editor

Story

Read more

Code

Example 2: Color Wheel with Neo Trinkey

Python
Copy the code to code.py in the CircuitPython root directory. Don't forget to put the mpy-file to the lib folder.
from cooperative_multitasking import Tasks
import board
from neopixel import NeoPixel
from touchio import TouchIn
from rainbowio import colorwheel

pixels = NeoPixel(board.NEOPIXEL, 4, brightness=0.1, auto_write=False)
touch1 = TouchIn(board.TOUCH1)
touch2 = TouchIn(board.TOUCH2)
colors = [0, 0, 0, 0]
tasks = Tasks()

def change_color(pixel):
    colors[pixel] = (1 + colors[pixel]) & 255
    pixels[pixel] = colorwheel(colors[pixel])
    pixels.show()

def change_color_0():
    change_color(0)
    tasks.after(107, change_color_0)

def change_color_1():
    change_color(1)
    tasks.after(127, change_color_1)

def change_color_2():
    change_color(2)
    tasks.after(149, change_color_2)

def change_color_3():
    change_color(3)
    tasks.after(167, change_color_3)

def is_touched():
    return touch1.value or touch2.value

def is_not_touched():
    return not (touch1.value or touch2.value)

def wait_for_color_reset():
    tasks.if_for_then(is_touched, 300, color_reset, priority=2)

def color_reset():
    for index in range(0, 4):
        colors[index] = 0
    tasks.if_then(is_not_touched, wait_for_color_reset, priority=2)

tasks.now(change_color_0)
tasks.now(change_color_1)
tasks.now(change_color_2)
tasks.now(change_color_3)
tasks.now(wait_for_color_reset)

while tasks.available():
    tasks.run()

Credits

Andreas Motzek
20 projects • 9 followers
I like algorithms, code, statistics and decisions based on them, solving difficult problems and, if possible, avoiding them elegantly.

Comments