# Circuit Playground or Hallowing Jack-o'-Lantern

## Halloween!

![](https://cdn-learn.adafruit.com/assets/assets/000/036/534/medium800/leds_lit.jpg?1476394251)

Claws-down, Halloween is my favorite holiday. Add some electronics to the mix and it’s an unstoppable force of nature.

In this simple **no-soldering-required** project we’ll make the Adafruit **Circuit Playground Classic** &nbsp;or **Circuit Playground Express** board act like a **flickering candle.** Pop this inside a jack-o’-lantern (or any other item that might normally use flame) to create a festive spooky atmosphere. (This can also work with an Adafruit **Hallowing** board with a NeoPixel strip plugged in the NEOPIX port.)

Sure, one can&nbsp;just _buy_ a fake battery-operated candle, but they’re usually pretty dim. Also, we can take this as&nbsp;an opportunity to learn a bit about code…and once Halloween’s over (_how sad!_) the Circuit Playground board can be _used again_ in endless&nbsp;_other_ projects.

 **Items needed:**

- Adafruit **[Circuit Playground Classic](https://www.adafruit.com/product/3000)** or **[Circuit Playground Express](https://www.adafruit.com/product/3333)** board.
- Either a **[3xAAA battery holder](https://www.adafruit.com/products/727)&nbsp;**_-or-_&nbsp;a **[USB phone charger](https://www.adafruit.com/products/1959)**&nbsp;& cable
- **Pumpkin** &nbsp;and **carving tools** , or other decorative&nbsp;item to&nbsp;illuminate (very effective with paper lanterns!)
- **Zip-Loc bag** , if using a real pumpkin

**If this is your first time using Circuit Playground, start with our “[Introducing Circuit Playground](../../../../introducing-circuit-playground)” or “[Circuit Playground Express](../../../../adafruit-circuit-playground-express)” guide.**&nbsp;There’s some software to set up on your computer and some procedures to learn.&nbsp;Try out a couple of the examples, make sure you know how to upload “sketches” (code) to the board.

Info: 

# Powering the Project
For stand-alone powering the project,&nbsp;our&nbsp;3xAAA battery holder has a power switch and a JST connector that fits&nbsp;the Circuit Playground board. A fresh set of batteries should run it for about ten&nbsp;hours, maybe even longer. Alternately, a USB phone charger (and micro-B cable) can be used.

![leds_727-03.jpg](https://cdn-learn.adafruit.com/assets/assets/000/036/506/medium640/leds_727-03.jpg?1476385961)

![](https://cdn-learn.adafruit.com/assets/assets/000/036/546/medium800thumb/leds_flicker2.jpg?1476420107)

# Circuit Playground or Hallowing Jack-o'-Lantern

## MakeCode

# **MakeCode** for Simulated Candle

Another option for&nbsp;Circuit Playground Express boards (not Classic) is **MakeCode** , a “block based” visual programming environment.

The basics of using MakeCode are explained in the **[Circuit Playground Express](../../../../adafruit-circuit-playground-express/makecode)**[guide](../../../../adafruit-circuit-playground-express/makecode).

https://makecode.com/_AAD3iigmb1PC

# Circuit Playground or Hallowing Jack-o'-Lantern

## CircuitPython Code

# **CircuitPython** &nbsp;Code for Simulated Candle
 **Circuit Python Express** &nbsp;boards can&nbsp;run **CircuitPython** &nbsp;— a different approach to programming compared to Arduino sketches.&nbsp;If you&nbsp;want to learn the basics of setting up and using CircuitPython, this is explained in the Circuit Playground Express&nbsp;**[CircuitPython guide](https://learn.adafruit.com/adafruit-circuit-playground-express/circuitpython-quickstart)**.

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

![circuitpython_leds_blinka.png](https://cdn-learn.adafruit.com/assets/assets/000/050/149/medium640/circuitpython_leds_blinka.png?1515819750)

Below is CircuitPython code that works&nbsp;similarly&nbsp;to the Arduino sketch shown elsewhere in this guide. To use this, plug Circuit Playground Express&nbsp;into USB…it should show up on your computer as a small **flash drive** …then edit the file **code.py** &nbsp;(or main.py) 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** &nbsp;(if not, see notes at the bottom of this page).

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

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Circuit_Playground_Jack_o_Lantern/jack_o_lantern_circuit_playground/code.py

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

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

# Circuit Playground or Hallowing Jack-o'-Lantern

## 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 also have the option of using MakeCode and CircuitPython as shown on prior pages.

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

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Circuit_Playground_Jack_o_Lantern/JackOLantern_CircuitPlayground/JackOLantern_CircuitPlayground.ino

&nbsp;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”!

If you have an Adafruit **Hallowing** board with a NeoPixel strip plugged into the NEOPIX port, you can use this version of the code instead:

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Circuit_Playground_Jack_o_Lantern/JackOLantern_HalloWing/JackOLantern_HalloWing.ino

# Circuit Playground or Hallowing Jack-o'-Lantern

## Pumpkins!

Now we need something to light up. Tradtionally this has been a carved pumpkin, but it doesn’t _have_ to be.&nbsp;If you’ve got a 3D printer, how about [this amazing Voronoi Skull](http://www.thingiverse.com/thing:1398223)? With our “candle” inside it&nbsp;should cast some interesting shadows!

If going the carved-pumpkin route, you’ll need a design…either your own, or an internet search for “pumpkin stencil” turns up _thousands_ of options, some free, some asking a small charge. Here’s a couple free ones I made that might get you started…

[Dragon_Stencil.pdf](https://cdn-learn.adafruit.com/assets/assets/000/036/478/original/Dragon_Stencil.pdf?1476340232)
[Werewolf_Stencil.pdf](https://cdn-learn.adafruit.com/assets/assets/000/036/479/original/Werewolf_Stencil.pdf?1476340245)
Both of these are designed with the “shallow carve” technique in mind, where one scoops away at the surface but doesn’t cut all the way through the pumpkin…they may&nbsp;work well&nbsp;enough for the latter, though&nbsp;you’d lose some smaller details like the dragon’s nostril or the werewolf’s slobber.

I tried out these foam craft pumpkins **WHICH TURNED OUT TO BE A HORRIBLE IDEA.** Fine for painting or for cut-through stencil designs, but nearly impossible to shallow carve! **Real gourds are best for that.**

**PRO TIP:** print out your design _first_ and take it with you when selecting a pumpkin. This ensures the size and shape will work with the design…you might even find a gourd&nbsp;with one&nbsp;slightly flatter&nbsp;side for the art.

![leds_punkins1.jpg](https://cdn-learn.adafruit.com/assets/assets/000/036/502/medium640/leds_punkins1.jpg?1476379136)

Various techniques can be used to transfer the flat art to the curved pumpkin…one could just “eyeball” it and redraw, or use a projector if&nbsp;available. Here I’ve scribbled on the back of the pattern with a soft pencil (6B), taped it down, then traced on the front with a ball-point pen to transfer some of the graphite to the pumpkin surface…this requires a bit of cleanup and re-interpreting bits of the art lost to creases.

![leds_punkins2.jpg](https://cdn-learn.adafruit.com/assets/assets/000/036/503/medium640/leds_punkins2.jpg?1476379632)

I also learned that white pumpkins are&nbsp;a poor choice_&nbsp;_for shallow-carving. They look great at night with a light&nbsp;inside…but in daylight, the design just vanishes!

Adding some black paint salvaged the “day look” of the white pumpkin, making the design “pop.” I liked it so much, the orange pumpkin (which didn’t really _need_ it) got the same treatment!

![leds_punkins3.jpg](https://cdn-learn.adafruit.com/assets/assets/000/036/504/medium640/leds_punkins3.jpg?1476382470)

Using a natural pumpkin? Place the Circuit Playground and battery pack inside a Zip-Loc sandwich bag to keep them clean.

![leds_ziploc.jpg](https://cdn-learn.adafruit.com/assets/assets/000/036/505/medium640/leds_ziploc.jpg?1476382770)

# Circuit Playground or Hallowing Jack-o'-Lantern

## How Does it Work?

The simulated flame code isn't very sophisticated or even technically accurate, yet does a good enough job of fooling our eyes. How can&nbsp;it do that? Fractals!

_Fractals_&nbsp;are mathematical objects exhibiting&nbsp;_self-similarity_&nbsp;at the macro and micro scales…any small part resembles the whole…

Fractals are great for simulating natural phenomena!

Notice how each floret of this (real) romanesco&nbsp;broccoli resembles the full head…and each floret, in turn, has smaller flor_ettes._

This notion&nbsp;of repetition across scales&nbsp;is used in computer simulations…for example, each peak and valley&nbsp;in this fractal terrain has several smaller sub-peaks, with progressively smaller mounds&nbsp;and nooks&nbsp;all the way down…but the _same mathematical formula_&nbsp;defines them at every level, only the scale changes.

_<sub>(Image credits: Wikimedia Commons public domain.)</sub>_

![leds_Fractal_Broccoli.jpg](https://cdn-learn.adafruit.com/assets/assets/000/036/433/medium640/leds_Fractal_Broccoli.jpg?1476321378)

![leds_Fractal_terrain_texture.jpg](https://cdn-learn.adafruit.com/assets/assets/000/036/434/medium640/leds_Fractal_terrain_texture.jpg?1476321386)

Fire is another natural phenomenon where this math could help. The flame code works a little like the fractal terrain, but much simpler. Instead of three dimensions, it only has to work in two (time and brightness), and one of those…time…always moves linearly forward. So really the code just has to create those “hills” and “valleys” along the brightness axis.

In the sketch, brightness is represented with a _uint8\_t_ variable — an 8-bit value in the range 0 to 255 (darkest to lightest). Consider&nbsp;two values&nbsp;randomly offset from the middle (128) up or down by 64 (or less). Those will be the starting and ending brightness for some time interval. Now consider a straight line between them…

Divide the line at its midpoint&nbsp;into two equal segments, then move that midpoint up or down randomly by up to half the previous range; somewhere between -32 and&nbsp;+32.

Do the same on each of the two resulting segments: split in two, randomly move the midpoint of each up or down by 16. Repeat with the four resulting segments, ±8, then eight segments ±4 and so forth…

![](https://cdn-learn.adafruit.com/assets/assets/000/036/435/medium800thumb/leds_fractal-anim.jpg?1476321411)

And that’s all there is to a simple fractal! Assign those numbers over time to the brightness of an LED&nbsp;(or all the NeoPixels around the Circuit Playground board) and you have a not-too-shabby&nbsp;candle flicker effect.

To achieve that line&nbsp;segment&nbsp;split, and the split-split, and split-split-split-split and so forth, the code uses a techniqe called _recursion._

Normally when programming you’ll call some function (e.g. Serial.println()), it performs some operation and then returns, and the code resumes at the next statement.

Recursion is what happens when a function _calls itself…_

```auto
void foo() {
  foo();
}
```

Normally this would create a sort of infinite loop, but even worse.

_Any_ time _any_&nbsp;C function is called, a tiny bit of RAM is used: a pointer back to the next statement upon return (called the _stack pointer_), plus space for any local variables used in that function. This RAM is freed when the function returns. If just keeps “nesting” calls and never returns though…the example above, despite being&nbsp;just a couple of bytes per function call...with only 2K RAM on most Arduino-type boards, it’ll run out of space in no time and the program will soon crash.

To avoid this, some limit can be placed on the maximum _depth_ of recursion…the number of times a function can call itself from within itself from within itself. This can be passed along as an argument…

```auto
void foo(int depth) {
  if(depth < 10) {
    foo(depth + 1);
  }
}
```

foo() now requires four bytes per invocation (two for the stack pointer, two for the “depth” argument…a local variable). The first call to foo() would pass a value of 0. By checking the value of depth and limiting it to 10, this won’t use more than 40 bytes worst case.

In the candle flame sketch, the split() function calls itself recursively, _twice_: one call handles the left or first half of the line segment, other handles the right or second half. Each of those, in turn, may call split() again, and so on…but only up to a point…

```auto
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 ...
  ...
}
```

“offset” is the maximum amount to move the center point up or down. Each time we call split() recursively, we divide that value by 2…because that’s the nature of fractals…big broccoli head = big offset, little broccoli florets = little offset. When offset reaches zero (which will happen due to integer rounding: 1÷2 = 0), no further subdivision/recursion takes place…a RAM disaster is averted and the LEDs are set to a brightness level corresponding to the “y1” argument before returning.

The code recurses and returns down and up and down and up like this until the final brightness level is reached, at which point this becomes&nbsp;the next starting value and a new random end value is chosen and the whole process is repeated.

 **The MakeCode version works a little differently, because this sort of recursion is not supported in “BLOCKS” mode. Instead the brightness level&nbsp;bounces back and forth semi-randomly…not quite the same, but still pretty effective.**


## Featured Products

### Circuit Playground Classic

[Circuit Playground Classic](https://www.adafruit.com/product/3000)
Would you like to learn electronics, with an all-in-one board that has sensors and LEDs built in? **Circuit Playground** is here - and it's the best way to practice programming on real hardware with no soldering or sewing required!

This is the **Classic**...

In Stock
[Buy Now](https://www.adafruit.com/product/3000)
[Related Guides to the Product](https://learn.adafruit.com/products/3000/guides)
### Circuit Playground Express

[Circuit Playground Express](https://www.adafruit.com/product/3333)
 **Circuit Playground Express** is the next step towards a perfect introduction to electronics and programming. We've taken the original Circuit Playground Classic and made it even better! Not only did we pack even more sensors in, we also made it even easier to...

In Stock
[Buy Now](https://www.adafruit.com/product/3333)
[Related Guides to the Product](https://learn.adafruit.com/products/3333/guides)
### 3 x AAA Battery Holder with On/Off Switch and 2-Pin JST

[3 x AAA Battery Holder with On/Off Switch and 2-Pin JST](https://www.adafruit.com/product/727)
This battery holder connects 3 AAA batteries together in series for powering all kinds of projects. We spec'd these out because the box is slim, and 3 AAA's add up to about 3.3-4.5V, a very similar range to Lithium Ion/polymer (Li-Ion) batteries and have an on-off switch. That makes...

In Stock
[Buy Now](https://www.adafruit.com/product/727)
[Related Guides to the Product](https://learn.adafruit.com/products/727/guides)
### Adafruit HalloWing M0 Express

[Adafruit HalloWing M0 Express](https://www.adafruit.com/product/3900)
[This is Hallowing..this is Hallowing... Hallowing! Hallowing!&nbsp;](https://www.youtube.com/watch?v=kGiYxCUAhks&t=39s)

Are you the kind of person who doesn't like taking down the skeletons and spiders until after January? Well, we've got the development board for...

In Stock
[Buy Now](https://www.adafruit.com/product/3900)
[Related Guides to the Product](https://learn.adafruit.com/products/3900/guides)
### Adafruit NeoPixel LED Strip with 3-pin JST PH 2mm Connector

[Adafruit NeoPixel LED Strip with 3-pin JST PH 2mm Connector](https://www.adafruit.com/product/3919)
Plug in and glow, this **Adafruit NeoPixel LED Strip with JST PH Connector** has **30 total LEDs** in a **"60 LED per meter" spacing** , and is 0.5 meters long, in classy Adafruit Black. Its not too long, but has lots of glowing action.<a...></a...>

Out of Stock
[Buy Now](https://www.adafruit.com/product/3919)
[Related Guides to the Product](https://learn.adafruit.com/products/3919/guides)

## Related Guides

- [Introducing Circuit Playground](https://learn.adafruit.com/introducing-circuit-playground.md)
- [Adafruit Circuit Playground Express](https://learn.adafruit.com/adafruit-circuit-playground-express.md)
- [Adafruit Hallowing M0](https://learn.adafruit.com/adafruit-hallowing.md)
- [Makey Paper Craft ](https://learn.adafruit.com/makey-paper-craft.md)
- [Sword & Wand Prop Effects with Circuit Playground](https://learn.adafruit.com/sword-and-wand-prop-effects-with-circuit-playground.md)
- [Motorized Marble Machine](https://learn.adafruit.com/marble-run.md)
- [Perfect Pitch Machine](https://learn.adafruit.com/perfect-pitch-machine.md)
- [How Cold Is It?](https://learn.adafruit.com/how-cold-is-it.md)
- [Tiny Museum Tour Device](https://learn.adafruit.com/tiny-museum-tour-device.md)
- [Make It Change: Potentiometers](https://learn.adafruit.com/make-it-change-potentiometers.md)
- [Dear Diary Alarm](https://learn.adafruit.com/dear-diary-alarm.md)
- [Light Paintbrush with Circuit Playground](https://learn.adafruit.com/lightpaint-cplay.md)
- [Making oscilloscope images with DACs](https://learn.adafruit.com/dac-oscilloscope-images.md)
- [Glowing Interactive Crystal Staff ](https://learn.adafruit.com/glowing-interactive-crystal-staff.md)
- [Stumble-Bot](https://learn.adafruit.com/stumble-bot-with-circuit-playground-and-crickit.md)
- [CRICKIT Snake Bot](https://learn.adafruit.com/crickit-snake-bot.md)
- [Circuit Playground Musical Glove](https://learn.adafruit.com/cpx-musical-glove.md)
- [Circuit Playground Express TV Zapper](https://learn.adafruit.com/circuitpython-tv-zapper-with-circuit-playground-express.md)
