Two LED Random Fader

This is a great little program if you want to have two red LEDs fade in and out slowly randomly of each other. Based on the Arduino Fade sample.

I used it to light up a Halloween thing. For example, you can use it for a pumpkin’s eyes.

/*
 Two Fade - Fades two LEDs independently at different rates
 Arduino Uno 
 
 Halloween 2013

 */

// NOTE: other end of LEDs are tied through 330 ohm resistor to +

int led1 = 9;           // the pin that the LED is attached to
int brightness1 = 180;  // how bright the LED is
int fadeAmount1 = 2;    // how many points to fade the LED by

int led2 = 10;          // the pin that the LED is attached to
int brightness2 = 60;   // how bright the LED is
int fadeAmount2 = 2;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup()  { 
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);  
} 

// the loop routine runs over and over again forever:
void loop()  { 
  analogWrite(led1, brightness1);    
  analogWrite(led2, brightness2);      

  fade(brightness1, fadeAmount1);
  fade(brightness2, fadeAmount2);  
}

void fade(int& brightness, int& fadeAmount) {
  // reverse the direction of the fading at the ends of the fade: 
  if (brightness <= (random(20,40) * 2) || brightness >= (random(110,120) * 2)) {
    fadeAmount = -fadeAmount ; 
  }     

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // change rate of brightness change depending on how bright
  // which allows smoother fades across all brightnesses
  if (brightness >= 200 && brightness <= 255) {
    delay(20);                            
  }
  else {
    delay(5);
  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>