Arduino Code

Arduino Code for Simulated Candle

This is the code you’ll use for Circuit Playground Classic. If you have a Circuit Playground Express, you can use this code as well, but have some additional options shown later.

Copy and paste the code below into a new Arduino sketch:

#include "Adafruit_CircuitPlayground.h"

void setup() {
  CircuitPlayground.begin();
  CircuitPlayground.setBrightness(255); // LEDs full blast!
}

uint8_t prev = 128;              // Start brightness in middle

void loop() {
  uint8_t lvl = random(64, 192); // End brightness at 128±64
  split(prev, lvl, 32);          // Start subdividing, ±32 at midpoint
  prev = lvl;                    // Assign end brightness to next start
}

void split(uint8_t y1, uint8_t y2, uint8_t offset) {
  if(offset) { // Split further into sub-segments w/midpoint at ±offset
    uint8_t mid = (y1 + y2 + 1) / 2 + random(-offset, offset);
    split(y1 , mid, offset / 2); // First segment (offset is halved)
    split(mid, y2 , offset / 2); // Second segment (ditto)
  } else { // No further subdivision - y1 determines LED brightness
    uint32_t c = (((int)(pow((float)y1 / 255.0, 2.7) * 255.0 + 0.5) // Gamma
                 * 0x1004004) >> 8) & 0xFF3F03; // Expand to 32-bit RGB color
    for(uint8_t i=0; i<10; i++) CircuitPlayground.strip.setPixelColor(i, c);
    CircuitPlayground.strip.show();
    delay(4);
  }
}

 From the “Tools” menu, select “Board→Adafruit Circuit Playground” (or Circuit Playground Express). Also make sure the correct serial port is selected, then upload the sketch to the board.

If all goes well, the NeoPixels on the Circuit Playground board should start flickering (mostly shades of yellow). There’s our electronic “candle”!

Last updated on Jan 13, 2018 Published on Oct 14, 2016