Skip to content

Instantly share code, notes, and snippets.

@BDFife
Created December 25, 2018 20:51
Show Gist options
  • Save BDFife/c9c7e0ec75358ab9a13349cf3431aa02 to your computer and use it in GitHub Desktop.
Save BDFife/c9c7e0ec75358ab9a13349cf3431aa02 to your computer and use it in GitHub Desktop.
Fairy Lamp Code Arduino (v2)
int redPin = 5;
int greenPin = 6;
int bluePin = 3;
int ledMax = 10;
int ledMin = 2;
int redVal = ledMin;
int greenVal = ledMin;
int blueVal = ledMin;
int redGoal = ledMax;
int greenGoal = ledMax;
int blueGoal = ledMax;
bool rest = false;
void setup() {
pinMode (redPin, OUTPUT);
pinMode (greenPin, OUTPUT);
pinMode (bluePin, OUTPUT);
randomSeed(analogRead(0));
}
void loop() {
if ((redVal == redGoal) &&
(blueVal == blueGoal) &&
(greenVal == greenGoal)) {
// We have reached target. Long delay then set new target.
delay(120);
redGoal = random(ledMin, ledMax);
greenGoal = random(ledMin, ledMax);
blueGoal = random(ledMin, ledMax);
}
else {
// Iterate towards target with a short delay.
redVal = adjVal(redGoal, redVal);
greenVal = adjVal(greenGoal, greenVal);
blueVal = adjVal(blueGoal, blueVal);
setColor(redVal, greenVal, blueVal);
delay(60);
}
}
int adjVal (int goal, int current) {
int adj = 0;
if (current < goal) {
adj = 1;
}
if (current > goal) {
adj = -1;
}
return (current + adj);
}
void setColor (int red, int green, int blue) {
// using common anode LED
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
analogWrite (redPin, red);
analogWrite (greenPin, green);
analogWrite(bluePin, blue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment