Skip to content

Instantly share code, notes, and snippets.

@JamieKnight
Created December 13, 2012 23:02
Show Gist options
  • Save JamieKnight/4280942 to your computer and use it in GitHub Desktop.
Save JamieKnight/4280942 to your computer and use it in GitHub Desktop.
Needed a single loop capable of looping from 0 - 255 and 255 to 0 for a LED fading function. If the type is "up" then i want it to go from 0 to 255, if the direction is down then i want it to go from 255 to 0. One loop, two directions no repeated code.
//better soltion
void fade(char type[], int pins[],){
//step though brightness in 255 steps, going up or down
for (int i = 0; i < 255; i++ ) {
int intensity = i;
if (type == "down") intensity = 255 - i;
//loop for each group of LEDs
for (int thisPin = 0; thisPin < 3; thisPin++) {
analogWrite(pins[thisPin], intensity);
}
}
}
//First solution
void fade(char type[], int pins[],){
//step though brightness in 255 steps, going up or down
if (type == "up") {
for (int i = 0; i < 255; i++ ) {
//loop through each LED in group
for (int thisPin = 0; thisPin < 3; thisPin++) {
analogWrite(pins[thisPin], i);
}
}
} else {
for (int i = 255; i > 0; i-- ) {
//loop through each LED in group
for (int thisPin = 0; thisPin < 3; thisPin++) {
analogWrite(pins[thisPin], i);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment