FastLED 3.9.15
Loading...
Searching...
No Matches
TwinkleFox.ino
Go to the documentation of this file.
1
4
5#include "FastLED.h"
6
7
8#define NUM_LEDS 100
9#define LED_TYPE WS2811
10#define COLOR_ORDER GRB
11#define DATA_PIN 3
12//#define CLK_PIN 4
13#define VOLTS 12
14#define MAX_MA 4000
15
16// Forward declarations
17void chooseNextColorPalette(CRGBPalette16& pal);
18void drawTwinkles(CRGBSet& L);
19CRGB computeOneTwinkle(uint32_t ms, uint8_t salt);
20uint8_t attackDecayWave8(uint8_t i);
21void coolLikeIncandescent(CRGB& c, uint8_t phase);
22
23
24// TwinkleFOX: Twinkling 'holiday' lights that fade in and out.
25// Colors are chosen from a palette; a few palettes are provided.
26//
27// This December 2015 implementation improves on the December 2014 version
28// in several ways:
29// - smoother fading, compatible with any colors and any palettes
30// - easier control of twinkle speed and twinkle density
31// - supports an optional 'background color'
32// - takes even less RAM: zero RAM overhead per pixel
33// - illustrates a couple of interesting techniques (uh oh...)
34//
35// The idea behind this (new) implementation is that there's one
36// basic, repeating pattern that each pixel follows like a waveform:
37// The brightness rises from 0..255 and then falls back down to 0.
38// The brightness at any given point in time can be determined as
39// as a function of time, for example:
40// brightness = sine( time ); // a sine wave of brightness over time
41//
42// So the way this implementation works is that every pixel follows
43// the exact same wave function over time. In this particular case,
44// I chose a sawtooth triangle wave (triwave8) rather than a sine wave,
45// but the idea is the same: brightness = triwave8( time ).
46//
47// Of course, if all the pixels used the exact same wave form, and
48// if they all used the exact same 'clock' for their 'time base', all
49// the pixels would brighten and dim at once -- which does not look
50// like twinkling at all.
51//
52// So to achieve random-looking twinkling, each pixel is given a
53// slightly different 'clock' signal. Some of the clocks run faster,
54// some run slower, and each 'clock' also has a random offset from zero.
55// The net result is that the 'clocks' for all the pixels are always out
56// of sync from each other, producing a nice random distribution
57// of twinkles.
58//
59// The 'clock speed adjustment' and 'time offset' for each pixel
60// are generated randomly. One (normal) approach to implementing that
61// would be to randomly generate the clock parameters for each pixel
62// at startup, and store them in some arrays. However, that consumes
63// a great deal of precious RAM, and it turns out to be totally
64// unnessary! If the random number generate is 'seeded' with the
65// same starting value every time, it will generate the same sequence
66// of values every time. So the clock adjustment parameters for each
67// pixel are 'stored' in a pseudo-random number generator! The PRNG
68// is reset, and then the first numbers out of it are the clock
69// adjustment parameters for the first pixel, the second numbers out
70// of it are the parameters for the second pixel, and so on.
71// In this way, we can 'store' a stable sequence of thousands of
72// random clock adjustment parameters in literally two bytes of RAM.
73//
74// There's a little bit of fixed-point math involved in applying the
75// clock speed adjustments, which are expressed in eighths. Each pixel's
76// clock speed ranges from 8/8ths of the system clock (i.e. 1x) to
77// 23/8ths of the system clock (i.e. nearly 3x).
78//
79// On a basic Arduino Uno or Leonardo, this code can twinkle 300+ pixels
80// smoothly at over 50 updates per seond.
81//
82// -Mark Kriegsman, December 2015
83
85
86// Overall twinkle speed.
87// 0 (VERY slow) to 8 (VERY fast).
88// 4, 5, and 6 are recommended, default is 4.
89#define TWINKLE_SPEED 4
90
91// Overall twinkle density.
92// 0 (NONE lit) to 8 (ALL lit at once).
93// Default is 5.
94#define TWINKLE_DENSITY 5
95
96// How often to change color palettes.
97#define SECONDS_PER_PALETTE 30
98// Also: toward the bottom of the file is an array
99// called "ActivePaletteList" which controls which color
100// palettes are used; you can add or remove color palettes
101// from there freely.
102
103// Background color for 'unlit' pixels
104// Can be set to CRGB::Black if desired.
106// Example of dim incandescent fairy light background color
107// CRGB gBackgroundColor = CRGB(CRGB::FairyLight).nscale8_video(16);
108
109// If AUTO_SELECT_BACKGROUND_COLOR is set to 1,
110// then for any palette where the first two entries
111// are the same, a dimmed version of that color will
112// automatically be used as the background color.
113#define AUTO_SELECT_BACKGROUND_COLOR 0
114
115// If COOL_LIKE_INCANDESCENT is set to 1, colors will
116// fade out slighted 'reddened', similar to how
117// incandescent bulbs change color as they get dim down.
118#define COOL_LIKE_INCANDESCENT 1
119
120
121CRGBPalette16 gCurrentPalette;
122CRGBPalette16 gTargetPalette;
123
124void setup() {
125 delay(3000); // safety startup delay
126 FastLED.setMaxPowerInVoltsAndMilliamps( VOLTS, MAX_MA);
128 .setCorrection(TypicalLEDStrip);
129
131}
132
133
148
149
150// This function loops over each pixel, calculates the
151// adjusted 'clock' that this pixel should use, and calls
152// "CalculateOneTwinkle" on each pixel. It then displays
153// either the twinkle color of the background color,
154// whichever is brighter.
156{
157 // "PRNG16" is the pseudorandom number generator
158 // It MUST be reset to the same starting value each time
159 // this function is called, so that the sequence of 'random'
160 // numbers that it generates is (paradoxically) stable.
161 uint16_t PRNG16 = 11337;
162
163 uint32_t clock32 = millis();
164
165 // Set up the background color, "bg".
166 // if AUTO_SELECT_BACKGROUND_COLOR == 1, and the first two colors of
167 // the current palette are identical, then a deeply faded version of
168 // that color is used for the background color
169 CRGB bg;
170 if( (AUTO_SELECT_BACKGROUND_COLOR == 1) &&
171 (gCurrentPalette[0] == gCurrentPalette[1] )) {
172 bg = gCurrentPalette[0];
173 uint8_t bglight = bg.getAverageLight();
174 if( bglight > 64) {
175 bg.nscale8_video( 16); // very bright, so scale to 1/16th
176 } else if( bglight > 16) {
177 bg.nscale8_video( 64); // not that bright, so scale to 1/4th
178 } else {
179 bg.nscale8_video( 86); // dim, scale to 1/3rd.
180 }
181 } else {
182 bg = gBackgroundColor; // just use the explicitly defined background color
183 }
184
185 uint8_t backgroundBrightness = bg.getAverageLight();
186
187 for( CRGB& pixel: L) {
188 PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
189 uint16_t myclockoffset16= PRNG16; // use that number as clock offset
190 PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
191 // use that number as clock speed adjustment factor (in 8ths, from 8/8ths to 23/8ths)
192 uint8_t myspeedmultiplierQ5_3 = ((((PRNG16 & 0xFF)>>4) + (PRNG16 & 0x0F)) & 0x0F) + 0x08;
193 uint32_t myclock30 = (uint32_t)((clock32 * myspeedmultiplierQ5_3) >> 3) + myclockoffset16;
194 uint8_t myunique8 = PRNG16 >> 8; // get 'salt' value for this pixel
195
196 // We now have the adjusted 'clock' for this pixel, now we call
197 // the function that computes what color the pixel should be based
198 // on the "brightness = f( time )" idea.
199 CRGB c = computeOneTwinkle( myclock30, myunique8);
200
201 uint8_t cbright = c.getAverageLight();
202 int16_t deltabright = cbright - backgroundBrightness;
203 if( deltabright >= 32 || (!bg)) {
204 // If the new pixel is significantly brighter than the background color,
205 // use the new color.
206 pixel = c;
207 } else if( deltabright > 0 ) {
208 // If the new pixel is just slightly brighter than the background color,
209 // mix a blend of the new color and the background color
210 pixel = blend( bg, c, deltabright * 8);
211 } else {
212 // if the new pixel is not at all brighter than the background color,
213 // just use the background color.
214 pixel = bg;
215 }
216 }
217}
218
219
220// This function takes a time in pseudo-milliseconds,
221// figures out brightness = f( time ), and also hue = f( time )
222// The 'low digits' of the millisecond time are used as
223// input to the brightness wave function.
224// The 'high digits' are used to select a color, so that the color
225// does not change over the course of the fade-in, fade-out
226// of one cycle of the brightness wave function.
227// The 'high digits' are also used to determine whether this pixel
228// should light at all during this cycle, based on the TWINKLE_DENSITY.
229CRGB computeOneTwinkle( uint32_t ms, uint8_t salt)
230{
231 uint16_t ticks = ms >> (8-TWINKLE_SPEED);
232 uint8_t fastcycle8 = ticks;
233 uint16_t slowcycle16 = (ticks >> 8) + salt;
234 slowcycle16 += sin8( slowcycle16);
235 slowcycle16 = (slowcycle16 * 2053) + 1384;
236 uint8_t slowcycle8 = (slowcycle16 & 0xFF) + (slowcycle16 >> 8);
237
238 uint8_t bright = 0;
239 if( ((slowcycle8 & 0x0E)/2) < TWINKLE_DENSITY) {
240 bright = attackDecayWave8( fastcycle8);
241 }
242
243 uint8_t hue = slowcycle8 - salt;
244 CRGB c;
245 if( bright > 0) {
246 c = ColorFromPalette( gCurrentPalette, hue, bright, NOBLEND);
247 if( COOL_LIKE_INCANDESCENT == 1 ) {
248 coolLikeIncandescent( c, fastcycle8);
249 }
250 } else {
251 c = CRGB::Black;
252 }
253 return c;
254}
255
256
257// This function is like 'triwave8', which produces a
258// symmetrical up-and-down triangle sawtooth waveform, except that this
259// function produces a triangle wave with a faster attack and a slower decay:
260//
261// / \
262// / \
263// / \
264// / \
265//
266
267uint8_t attackDecayWave8( uint8_t i)
268{
269 if( i < 86) {
270 return i * 3;
271 } else {
272 i -= 86;
273 return 255 - (i + (i/2));
274 }
275}
276
277// This function takes a pixel, and if its in the 'fading down'
278// part of the cycle, it adjusts the color a little bit like the
279// way that incandescent bulbs fade toward 'red' as they dim.
280void coolLikeIncandescent( CRGB& c, uint8_t phase)
281{
282 if( phase < 128) return;
283
284 uint8_t cooling = (phase - 128) >> 4;
285 c.g = qsub8( c.g, cooling);
286 c.b = qsub8( c.b, cooling * 2);
287}
288
289// A mostly red palette with green accents and white trim.
290// "CRGB::Gray" is used as white to keep the brightness more uniform.
296
297// A mostly (dark) green palette with red berries.
298#define Holly_Green 0x00580c
299#define Holly_Red 0xB00402
306
307// A red and white striped palette
308// "CRGB::Gray" is used as white to keep the brightness more uniform.
314
315// A mostly blue palette with white accents.
316// "CRGB::Gray" is used as white to keep the brightness more uniform.
322
323// A pure "fairy light" palette with some brightness variations
324#define HALFFAIRY ((CRGB::FairyLight & 0xFEFEFE) / 2)
325#define QUARTERFAIRY ((CRGB::FairyLight & 0xFCFCFC) / 4)
331
332// A palette of soft snowflakes with the occasional bright one
334{ 0x304048, 0x304048, 0x304048, 0x304048,
335 0x304048, 0x304048, 0x304048, 0x304048,
336 0x304048, 0x304048, 0x304048, 0x304048,
337 0x304048, 0x304048, 0x304048, 0xE0F0FF };
338
339// A palette reminiscent of large 'old-school' C9-size tree lights
340// in the five classic colors: red, orange, green, blue, and white.
341#define C9_Red 0xB80400
342#define C9_Orange 0x902C02
343#define C9_Green 0x046002
344#define C9_Blue 0x070758
345#define C9_White 0x606820
353
354// A cold, icy pale blue palette
355#define Ice_Blue1 0x0C1040
356#define Ice_Blue2 0x182080
357#define Ice_Blue3 0x5080C0
365
366
367// Add or remove palette names from this list to control which color
368// palettes are used, and in what order.
381
382
383// Advance to the next color palette in the list (above).
384void chooseNextColorPalette( CRGBPalette16& pal)
385{
386 const uint8_t numberOfPalettes = sizeof(ActivePaletteList) / sizeof(ActivePaletteList[0]);
387 static uint8_t whichPalette = -1;
388 whichPalette = addmod8( whichPalette, 1, numberOfPalettes);
389
390 pal = *(ActivePaletteList[whichPalette]);
391}
void setup()
void loop()
#define COLOR_ORDER
#define NUM_LEDS
fl::CRGB leds[NUM_LEDS]
#define DATA_PIN
Definition ClientReal.h:82
FL_DISABLE_WARNING_PUSH FL_DISABLE_WARNING_GLOBAL_CONSTRUCTORS CFastLED FastLED
Global LED strip management instance.
#define MAX_MA
void coolLikeIncandescent(CRGB &c, uint8_t phase)
#define C9_Blue
CRGBPalette16 gTargetPalette
#define C9_Green
void chooseNextColorPalette(CRGBPalette16 &pal)
const TProgmemRGBPalette16 Ice_p
#define C9_Red
uint8_t attackDecayWave8(uint8_t i)
#define Holly_Red
const TProgmemRGBPalette16 RedWhite_p
#define Holly_Green
const TProgmemRGBPalette16 FairyLight_p
const TProgmemRGBPalette16 RedGreenWhite_p
#define Ice_Blue3
void drawTwinkles(CRGBSet &L)
#define C9_White
const TProgmemRGBPalette16 * ActivePaletteList[]
#define Ice_Blue1
#define HALFFAIRY
#define QUARTERFAIRY
const TProgmemRGBPalette16 BlueWhite_p
CRGBPalette16 gCurrentPalette
CRGB gBackgroundColor
#define Ice_Blue2
const TProgmemRGBPalette16 Holly_p
const TProgmemRGBPalette16 RetroC9_p
const TProgmemRGBPalette16 Snow_p
#define C9_Orange
CRGB computeOneTwinkle(uint32_t ms, uint8_t salt)
#define LED_TYPE
uint8_t hue
Definition advanced.h:94
A version of CPixelView<CRGB> with an included array of CRGB LEDs.
Definition pixelset.h:496
CRGB ColorFromPalette(const CRGBPalette16 &pal, fl::u8 index, fl::u8 brightness, TBlendType blendType)
CRGB blend(const CRGB &p1, const CRGB &p2, fract8 amountOfP2)
void nblendPaletteTowardPalette(CRGBPalette16 &current, CRGBPalette16 &target, fl::u8 maxChanges)
fl::u32 TProgmemRGBPalette16[16]
CRGBPalette16 entries stored in PROGMEM memory.
#define FL_PROGMEM
PROGMEM keyword for storage.
@ TypicalLEDStrip
Typical values for SMD5050 LEDs.
Definition color.h:15
fl::CRGB CRGB
Definition crgb.h:25
const TProgmemRGBPalette16 PartyColors_p
HSV color ramp: blue, purple, pink, red, orange, yellow (and back).
const TProgmemRGBPalette16 RainbowColors_p
HSV Rainbow.
#define EVERY_N_MILLISECONDS(N)
Alias for EVERY_N_MILLIS.
Definition lib8tion.h:1045
#define EVERY_N_SECONDS(N)
Checks whether to execute a block of code every N seconds.
Definition lib8tion.h:1010
#define VOLTS
Definition old.h:22
CPixelView< CRGB > CRGBSet
CPixelView specialized for CRGB pixel arrays - the most commonly used pixel view type.
Definition pixelset.h:51
FASTLED_FORCE_INLINE u8 getAverageLight() const FL_NOEXCEPT
Get the average of the R, G, and B values.
Definition crgb.hpp:152
@ FairyLight
<div style='background:#FFE42D;width:4em;height:4em;'></div>
Definition crgb.h:655
@ Green
<div style='background:#008000;width:4em;height:4em;'></div>
Definition crgb.h:558
@ Red
<div style='background:#FF0000;width:4em;height:4em;'></div>
Definition crgb.h:622
@ Blue
<div style='background:#0000FF;width:4em;height:4em;'></div>
Definition crgb.h:512
@ Gray
<div style='background:#808080;width:4em;height:4em;'></div>
Definition crgb.h:556
@ Black
<div style='background:#000000;width:4em;height:4em;'></div>
Definition crgb.h:510
FASTLED_FORCE_INLINE CRGB & nscale8_video(u8 scaledown) FL_NOEXCEPT
Scale down a RGB to N/256ths of it's current brightness using "video" dimming rules.
Definition crgb.hpp:72
#define TWINKLE_SPEED
Definition twinklefox.h:85
#define AUTO_SELECT_BACKGROUND_COLOR
Definition twinklefox.h:99
#define TWINKLE_DENSITY
Definition twinklefox.h:90
#define COOL_LIKE_INCANDESCENT
Definition twinklefox.h:104
#define SECONDS_PER_PALETTE
Definition twinklefox.h:93