CD-PC Website Arduino Neopixel random fade


Description:
Neopixel shield test with random() and fading

Code works on a Arduino Uno v3

Code:

// Full Color LED random color generator with fade

byte RedLED = 2;      //red led pwm output
byte BluLED = 3;      //blue led pwm output
byte GrnLED = 4;      //green led pwm output
int  RedRnd;          //rnd red value
int  BluRnd;          //rnd green value
int  GrnRnd;          //rnd blue value
int  RedFade=0;       //red fade value
int  BluFade=0;       //blue fade value
int  GrnFade=0;       //green fade value
int  RedFadeStep=5; //red next step value
int  BluFadeStep=5; //blue next step value
int  GrnFadeStep=5; //green next step value

unsigned long prevMillis = 0;       //last time LED rnd was updated
unsigned long prevMillisFade = 0;   //last time LED fade was updated
unsigned long curMillis=0;          //current time in milli seconds
const long interval = 10000;        //next rnd update
const long intervalFade = 50;       //fade update

void setup ()
{
  randomSeed(analogRead(A0));
  pinMode (RedLED, OUTPUT);
  pinMode (BluLED, OUTPUT);
  pinMode (GrnLED, OUTPUT);
}

void loop ()
{
  curMillis = millis(); // get current milliseconds

  if (curMillis - prevMillis >= interval) //needs a rnd update?
  {
    prevMillis = curMillis;
    RedRnd = random(255);
    BluRnd = random(255);
    GrnRnd = random(255);
  }

  if (curMillis - prevMillisFade >= intervalFade) //needs a fade update?
  {
    prevMillisFade = curMillis;
    //fade value + (or -) step
    RedFade+=RedFadeStep;
    GrnFade+=GrnFadeStep;
    BluFade+=BluFadeStep;
    
    //Now mix the colors 
    analogWrite(RedLED,RedFade);
    analogWrite(BluLED,BluFade);
    analogWrite(GrnLED,GrnFade);

  //if fade <=0 or >=rnd value then switch direction
    if (RedFade <= 0 || RedFade >= RedRnd)   {      RedFadeStep = -RedFadeStep ;   }
    if (GrnFade <= 0 || GrnFade >= GrnRnd)   {      GrnFadeStep = -GrnFadeStep ;   }
    if (BluFade <= 0 || BluFade >= BluRnd)   {      BluFadeStep = -BluFadeStep ;   }
  }
}

Status: Final.

Last page update: 29-05-2016