Andreas Motzek
Published © CC BY

Complex behaving Hardware with CircuitPython - Part I

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

BeginnerProtip1 hour105
Complex behaving Hardware with CircuitPython - Part I

Things used in this project

Hardware components

Adafruit Gemma M0
×1

Software apps and online services

Mu Editor

Story

Read more

Code

Example 1: Blink with Gemma M0

Python
Copy the code to code.py in the CircuitPython root directory. Don't forget to put the three mpy-files to the lib folder.
from random import randint
from cooperative_multitasking import Tasks
import board
from adafruit_dotstar import DotStar

tasks = Tasks()
dotstar = DotStar(board.APA102_SCK, board.APA102_MOSI, 1, auto_write=False)
colors = [(48, 0, 0), (40, 40, 0), (0, 48, 0), (0, 0, 64), (32, 0, 64)]

def on():
    index = randint(0, len(colors) - 1)
    color = colors[index]
    dotstar.fill(color)
    dotstar.show()
    tasks.after(1000, off)

def off():
    dotstar.fill((1, 1, 1))
    dotstar.show()
    tasks.after(2000, on)
    
tasks.now(on)

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