#include <Adafruit_NeoPixel.h>
#define PIN 6
#define NUMPIXELS 64
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
struct PixelState {
uint8_t r, g, b; // base color
float brightness; // 0.0 to 1.0
int direction; // 1 = fade in, -1 = fade out
unsigned long lastUpdate; // last fade update
int fadeSpeed; // ms between brightness steps
};
PixelState pixelStates[NUMPIXELS];
void setup() {
pixels.begin();
pixels.show();
for (int i = 0; i < NUMPIXELS; i++) {
pixelStates[i].r = random(0, 255);
pixelStates[i].g = random(0, 255);
pixelStates[i].b = random(0, 255);
pixelStates[i].brightness = 0.0;
pixelStates[i].direction = 1; // start fading in
pixelStates[i].lastUpdate = millis();
pixelStates[i].fadeSpeed = random(10, 30); // speed of fade steps
}
}
void loop() {
unsigned long currentMillis = millis();
for (int i = 0; i < NUMPIXELS; i++) {
if (currentMillis - pixelStates[i].lastUpdate >= pixelStates[i].fadeSpeed) {
pixelStates[i].lastUpdate = currentMillis;
// adjust brightness
pixelStates[i].brightness += 0.02 * pixelStates[i].direction;
if (pixelStates[i].brightness >= 1.0) {
pixelStates[i].brightness = 1.0;
pixelStates[i].direction = -1; // start fading out
} else if (pixelStates[i].brightness <= 0.0) {
pixelStates[i].brightness = 0.0;
pixelStates[i].direction = 1; // start fading in again
// pick a new random color
pixelStates[i].r = random(0, 255);
pixelStates[i].g = random(0, 255);
pixelStates[i].b = random(0, 255);
pixelStates[i].fadeSpeed = random(10, 30);
}
// apply brightness scaling
uint8_t rVal = pixelStates[i].r * pixelStates[i].brightness;
uint8_t gVal = pixelStates[i].g * pixelStates[i].brightness;
uint8_t bVal = pixelStates[i].b * pixelStates[i].brightness;
pixels.setPixelColor(i, pixels.Color(rVal, gVal, bVal));
}
}
pixels.show();
}