Skip to content

Instantly share code, notes, and snippets.

@scoates
Created November 12, 2021 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scoates/28498fcdf113cc391afe2a2ff402a60c to your computer and use it in GitHub Desktop.
Save scoates/28498fcdf113cc391afe2a2ff402a60c to your computer and use it in GitHub Desktop.
Twinkling tree LEDs?
#include <FastLED.h>
#define NUM_LEDS 150
#define LED_PIN 25
#define BRIGHTNESS 50
#define RED 0
#define GREEN 1
#define WHITE 2
#define OFF 3
#define MIN_FADE 100
#define MIN_START 200
#define UPDATE_FREQ 50
#define OFF_MOD 10
CRGB leds[NUM_LEDS];
uint8_t ledPalette[NUM_LEDS];
uint8_t ledColorIndex[NUM_LEDS];
uint8_t ledNextFade[NUM_LEDS];
// these palettes waste memory, but:
// 1) there's nothing else running in this memory, and
// 2) the added flexibility is worth it because of (1)
DEFINE_GRADIENT_PALETTE(red_gp) {
0, 0, 0, 0, // black
160, 255, 0, 0, // red
255, 0, 0, 0 // black
};
DEFINE_GRADIENT_PALETTE(green_gp) {
0, 0, 0, 0, // black
160, 0, 255, 0, // green
255, 0, 0, 0 // black
};
DEFINE_GRADIENT_PALETTE(white_gp) {
0, 0, 0, 0, // black
160, 255, 255, 255, // white
255, 0, 0, 0 // black
};
CRGBPalette16 palettes[3] = {red_gp, green_gp, white_gp};
bool is_off(CRGB led) {
return led.r == 0 && led.g == 0 && led.b == 0;
}
void seed_leds() {
for (uint8_t i = 0; i < NUM_LEDS; i++) {
// ignore leds that already have a colour
if (!is_off(leds[i])) {
continue;
}
// chance of being red, green, white, or weighted to stay off
int pal = random8() % OFF_MOD;
if (pal >= OFF) {
continue;
} else {
ledPalette[i] = pal;
ledColorIndex[i] = min((uint8_t) MIN_START, random8());
ledNextFade[i] = min((uint8_t) MIN_FADE, random8());
leds[i] = ColorFromPalette(palettes[ledPalette[i]], ledColorIndex[i]);
}
}
}
void fade_leds() {
for (uint8_t i = 0; i < NUM_LEDS; i++) {
if (is_off(leds[i])) {
continue;
}
if (ledNextFade[i] > 0) {
// don't fade yet
ledNextFade[i]--;
} else {
// fade
leds[i] = ColorFromPalette(palettes[ledPalette[i]], ledColorIndex[i]--);
}
}
}
void setup() {
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
FastLED.clear(true);
seed_leds();
}
void loop() {
EVERY_N_MILLISECONDS(UPDATE_FREQ) {
fade_leds();
seed_leds();
FastLED.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment