Fading code for Light Box tutorial - lesson 3

For makers who have purchased an Adafruit Starter Pack, get help with the tutorials here!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
greenleaf
 
Posts: 21
Joined: Sat Jun 25, 2011 10:18 pm

Fading code for Light Box tutorial - lesson 3

Post by greenleaf »

After completing lesson 3, I decided to write a new version that fades the LEDs gradually, giving a softer transition effect. Here's the code if anyone wants to play around with it. (Note that I'm using pins 9, 10, and 11 instead of 10,11, and 12, because pin 12 was giving me some problems). This code uses functions which are a little more advanced but you should be able to make sense of it:

Code: Select all

/*
  Light Box
  Rotates red, green, and blue LEDs through a cycle.  Looks pretty 
  inside a light box or jar.
 */

int redPin = 11;                  // Red LED connected to digital pin 12
int greenPin = 10;                // Green LED connected to digital pin 11
int bluePin = 9;                 // Blue LED connected to digital pin 10
int firstRun = 1;

void setup()                      // run once, when the sketch starts
{
  pinMode(redPin, OUTPUT);        // sets the digital pin as output
  pinMode(greenPin, OUTPUT);      // sets the digital pin as output
  pinMode(bluePin, OUTPUT);      // sets the digital pin as output
}

//  This function fades in the LED
void fadeIn(int led){
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) { 
  analogWrite(led, fadeValue);   
  delay(60);  // Change this to make the fade in slower or faster
  }
}

//  This function fades out the LED
void fadeOut(int led){
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) { 
  analogWrite(led, fadeValue);   
  delay(60);  // Change this to make the fade out slower or faster
  }
}

void loop(){                  // run over and over again
if (firstRun == 1) {          // if this is the first iteration, start with red
  fadeIn(redPin);
  delay(3000);
  firstRun = 0;
}
fadeIn(greenPin);
delay(3000); // RED + GREEN
fadeOut(redPin);
delay(3000); // GREEN
fadeIn(bluePin);
delay(3000); // GREEN + BLUE
fadeOut(greenPin);
delay(3000); // BLUE
fadeIn(redPin);
delay(3000); // RED+BLUE
fadeOut(bluePin);
delay(3000); // RED
}

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino Starter Pack”