Skip to content

Instantly share code, notes, and snippets.

@adrianstevens
Created September 28, 2021 00:17
Show Gist options
  • Save adrianstevens/5723c2c5b08a914cc95f4d83a9fcabf7 to your computer and use it in GitHub Desktop.
Save adrianstevens/5723c2c5b08a914cc95f4d83a9fcabf7 to your computer and use it in GitHub Desktop.
Snippet showing comet effect on a APA102 RGB led strip light powered by Wilderness Labs Meadow
void Comet(Apa102 ledStrip)
{
Random rand = new Random();
int length1 = 1;
float position1 = 0;
float speed1 = 1f;
Color cometColor1 = Color.Cyan;
int length2 = 1;
float position2 = 50;
float speed2 = 1.1f;
Color cometColor2 = Color.Cyan.WithHue(90);
Color[] colors = new Color[ledStrip.NumberOfLeds];//store a color value for every LED
//initialize to black
for (int j = 0; j < ledStrip.NumberOfLeds; j++) { colors[j] = Color.Black; }
//run the comets
while (true)
{
//move the comets
position1 += speed1;
position2 += speed2;
//bounds check - change direction at the ends of the strip
if (position1 >= ledStrip.NumberOfLeds - length1 || position1 <= 0) { speed1 *= -1; }
if (position2 >= ledStrip.NumberOfLeds - length2 || position2 <= 0) { speed2 *= -1; }
//increment the hue/color
cometColor1 = cometColor1.WithHue(cometColor1.Hue + 0.0001);
if (cometColor1.Hue >= 1.0) cometColor1 = cometColor1.WithHue(0);
cometColor2 = cometColor2.WithHue(cometColor2.Hue + 0.00011); //10% faster than comet 1
if (cometColor2.Hue >= 1.0) cometColor2 = cometColor2.WithHue(0);
//update the LEDs
for (int j = 0; j < ledStrip.NumberOfLeds; j++)
{
// draw comets overlapping
if (j >= position2 && j < position2 + length2 &&
j >= position1 && j < position1 + length1)
{ //if both comets are on the same LED - color blend
colors[j] = new Color((cometColor1.R + cometColor2.R)/2,
(cometColor1.G + cometColor2.G)/2,
(cometColor1.B + cometColor2.B)/2);
}
//draw comet 1
else if (j >= position1 && j < position1 + length1)
{ //set the LED at comet 1's position to its current color
colors[j] = cometColor1;
}
//draw comet 2
else if (j >= position2 && j < position2 + length2)
{ //set the LED at comet 2's position to its current color
colors[j] = cometColor2;
}
//fade everything else randomly
else if (rand.Next() % 3 == 0)
{
colors[j] = colors[j].WithBrightness(colors[j].Brightness - 0.1);
}
ledStrip.SetLed(j, colors[j]);
}
ledStrip.Show();
Thread.Sleep(25);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment