cookbook/recipes/twinkle.md
Difficulty Level: ⭐⭐ Intermediate Time to Complete: 25-35 minutes Prerequisites:
You'll Learn:
Random twinkling stars and sparkle effects.
Basic twinkling effect with random colors:
void twinkle() {
// Fade all LEDs slightly
fadeToBlackBy(leds, NUM_LEDS, 32);
// Add new twinkles
if (random8() < 50) { // 50/255 chance per frame
int pos = random16(NUM_LEDS);
leds[pos] = CHSV(random8(), 200, 255); // Random color
}
}
Twinkle effect with a specific color:
void coloredTwinkle(CRGB color) {
fadeToBlackBy(leds, NUM_LEDS, 20);
// Add multiple twinkles per frame
for (int i = 0; i < 3; i++) {
if (random8() < 100) {
int pos = random16(NUM_LEDS);
leds[pos] = color;
leds[pos].fadeToBlackBy(random8(50, 150)); // Vary brightness
}
}
}
Quick flashing sparkles on a dark background:
void sparkle(CRGB color, int count, int delayMs) {
// Turn off all LEDs
FastLED.clear();
// Flash random LEDs
for (int i = 0; i < count; i++) {
int pos = random16(NUM_LEDS);
leds[pos] = color;
}
FastLED.show();
delay(delayMs);
}
Warm white background with bright white twinkles:
void whiteTwinkle() {
// Background: warm white
for (int i = 0; i < NUM_LEDS; i++) {
leds[i] = CRGB(255, 147, 41);
leds[i].fadeToBlackBy(200); // Dim background
}
// Random bright twinkles
for (int i = 0; i < 5; i++) {
if (random8() < 80) {
int pos = random16(NUM_LEDS);
leds[pos] = CRGB::White;
}
}
FastLED.show();
delay(100);
}
The twinkle effect creates a starry night appearance by:
Fade rate (in fadeToBlackBy): How quickly LEDs dim
Probability (in random8() check): How often new twinkles appear
Count: Number of simultaneous sparkles
For a starfield effect:
void loop() {
fadeToBlackBy(leds, NUM_LEDS, 32);
if (random8() < 30) {
leds[random16(NUM_LEDS)] = CRGB::White;
}
FastLED.show();
delay(20);
}
For party lights:
void loop() {
fadeToBlackBy(leds, NUM_LEDS, 50);
for (int i = 0; i < 5; i++) {
if (random8() < 100) {
leds[random16(NUM_LEDS)] = CHSV(random8(), 255, 255);
}
}
FastLED.show();
delay(50);
}
For fireflies:
void loop() {
fadeToBlackBy(leds, NUM_LEDS, 10); // Very slow fade
if (random8() < 20) {
leds[random16(NUM_LEDS)] = CRGB(255, 255, 100); // Yellowish
}
FastLED.show();
delay(30);
}
Palette-Based Twinkle:
void paletteTwinkle(CRGBPalette16 palette) {
fadeToBlackBy(leds, NUM_LEDS, 40);
if (random8() < 60) {
int pos = random16(NUM_LEDS);
leds[pos] = ColorFromPalette(palette, random8(), 255, LINEARBLEND);
}
}
Twinkling Rainbow:
void rainbowTwinkle() {
fadeToBlackBy(leds, NUM_LEDS, 30);
if (random8() < 80) {
int pos = random16(NUM_LEDS);
leds[pos] = CHSV(random8(), 255, 255);
}
}