Skip to content

Instantly share code, notes, and snippets.

Created March 22, 2014 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4c8ea9108a494b71fed9 to your computer and use it in GitHub Desktop.
Save anonymous/4c8ea9108a494b71fed9 to your computer and use it in GitHub Desktop.
LED Crossfade function for Processing and Arduino
/*////////////////////////////////////////////////////////////////
LED CROSSFADE FUNCTION
Requirements:
• RGB LED Arduino circuit
• Written for Processing's Arduino/Firmata library
• Can be reconfigured for Arduino (without Firmata)
by removing "arduino." before the "analogWrite" functions
Syntax:
LEDcrossFade(RedPin, GreenPin, BluePin,
StartingR, StartingG, StartingB,
DestinationR, DestinationG, DestinationB,
Steps, Duration)
Parameters:
• Red/Green/BluePin - The pin numbers/variables associated with
the RGB LED
• StartingR/G/B - The RGB value you want to fade FROM
• DestinationR/G/b - The RGB value you want to fade TO
• Steps - Number of steps transition is broken into
(higher the value, the smoother the fade)
• Duration - Total duration of fade (in milliseconds)
Example:
"LEDcrossFade(9,10,11, 0,0,0, 255,255,255, 20,2000);"
This will fade an RGB LED that's connected to pins 9, 10, and 11
from off (0,0,0) to white (255,255,255) in 20 steps over 2 seconds
/////////////////////////////////////////////////////////////////*/
void LEDcrossFade(int RedPin, int GreenPin, int BluePin,
int StartingR, int StartingG, int StartingB,
int DestinationR, int DestinationG, int DestinationB,
int Steps, int Duration) {
// break fade into Steps to determine smoothness of the transition
// and find the amount of change for each color, each step
// in order to reach the destination in the given amount of steps
float RchangePerStep = (DestinationR - StartingR)/Steps;
float GchangePerStep = (DestinationG - StartingG)/Steps;
float BchangePerStep = (DestinationB - StartingB)/Steps;
// loop through each step, displaying each color, then
// increment each color by the given amount of change per step
// to prepare for the next step
for (int i = 0; i < Steps; i++){
arduino.analogWrite(RedPin, StartingR);
arduino.analogWrite(GreenPin, StartingG);
arduino.analogWrite(BluePin, StartingB);
StartingR += RchangePerStep;
StartingG += GchangePerStep;
StartingB += BchangePerStep;
// ensures that the last step brings the LED exactly to the
// destination color, compensating for any messy fractions.
if(i == Steps-1){
arduino.analogWrite(RedPin, DestinationR);
arduino.analogWrite(GreenPin, DestinationG);
arduino.analogWrite(BluePin, DestinationB);
}
// delay each step long enough to reach the last step
// by the desired duration
delay(Duration/Steps);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment