CircuitPython Code for Simulated Candle

Circuit Python Express boards can run CircuitPython — a different approach to programming compared to Arduino sketches. If you want to learn the basics of setting up and using CircuitPython, this is explained in the Circuit Playground Express CircuitPython guide.

This is for Express boards only; Classic boards can’t run CircuitPython.

Below is CircuitPython code that works similarly to the Arduino sketch shown elsewhere in this guide. To use this, plug Circuit Playground Express into USB…it should show up on your computer as a small flash drive…then edit the file (or with your text editor of choice. Select and copy the code below and paste it into that file, entirely replacing its contents (don’t mix it in with lingering bits of old code). When you save the file, the code should start running almost immediately (if not, see notes at the bottom of this page).

If Circuit Playground Express doesn’t show up as a drive, follow the guide link above to prepare the board for CircuitPython.

# SPDX-FileCopyrightText: 2018 Phillip Burgess for Adafruit Industries
# SPDX-License-Identifier: MIT

"""Jack-o'-Lantern flame example Adafruit Circuit Playground Express"""

import math
import board
import neopixel
    import urandom as random  # for v1.0 API support
except ImportError:
    import random

NUMPIX = 10        # Number of NeoPixels
PIXPIN = board.D8  # Pin where NeoPixels are connected
STRIP = neopixel.NeoPixel(PIXPIN, NUMPIX, brightness=1.0)
PREV = 128

def split(first, second, offset):
    Subdivide a brightness range, introducing a random offset in middle,
    then call recursively with smaller offsets along the way.
    @param1 first:  Initial brightness value.
    @param1 second: Ending brightness value.
    @param1 offset: Midpoint offset range is +/- this amount max.
    if offset != 0:
        mid = ((first + second + 1) / 2 + random.randint(-offset, offset))
        offset = int(offset / 2)
        split(first, mid, offset)
        split(mid, second, offset)
        level = math.pow(first / 255.0, 2.7) * 255.0 + 0.5
        STRIP.fill((int(level), int(level / 8), int(level / 48)))

while True:  # Loop forever...
    LVL = random.randint(64, 191)
    split(PREV, LVL, 32)
    PREV = LVL

This code can also work on an Adafruit HalloWing board with just a small change to lines 10 and 11:

NUMPIX = 30                       # Number of NeoPixels
PIXPIN = board.EXTERNAL_NEOPIXEL  # Pin where NeoPixels are connected

This guide was first published on Oct 14, 2016. It was last updated on Jul 17, 2024.

This page (CircuitPython Code) was last updated on Jul 17, 2024.

Text editor powered by tinymce.