NEO Pixels Random Colors

I finally got some NeoPixels and been having a lot of fun with them and when looking for a good example I came across a posting on this forum.. however it is now locked since it has been more than 120 days.

So I wanted to share a solution I wrote for fun that others might find useful like I was looking for before learning it.

#include <Adafruit_NeoPixel.h>

#define PIN 3       // GPIO pin the neopixels are attached
#define NUMPIXELS 2 // number of pixels

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

const int COLOR_COUNT = 5;
enum colors { RED = 0, GREEN, BLUE, YELLOW, PURPLE };

const int SLEEP_AMOUNT = 1000;  //wait until changing the next random pixel
const uint8_t BRIGHTNESS = 50;        //0-255 scale

void setup()
{
    pixels.begin();
}
 
void loop()
{   
    // Method 1: pick a random pixel and change it
    // int pixelId = random(pixels.numPixels());
    // pixels.setPixelColor(pixelId, getRandomColor());
     
    // Method 2: change every pixel to a random color
    for(int i = 0; i < pixels.numPixels(); i++)
    {
        pixels.setPixelColor(i, getRandomColor());    
    }
    
    pixels.setBrightness(BRIGHTNESS);  
    pixels.show();

    delay(SLEEP_AMOUNT);
}

uint32_t getRandomColor()
{    
    switch(random(COLOR_COUNT))
    {
        case RED:    { return pixels.Color(255, 0, 0);   }
        case GREEN:  { return pixels.Color(0, 255, 0);   }
        case BLUE:   { return pixels.Color(0, 0, 255);   }
        case YELLOW: { return pixels.Color(255, 255, 0); }
        case PURPLE: { return pixels.Color(255, 0, 255); }
        
        // should never happen
        default:{ return pixels.Color(255, 255, 255); }
    }  
}

NeoPixels.ino (1.47 KB)

2 Likes

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.