I'm trying to create a function that takes two colours and creates a smooth gradient between them one colour at the beginning and one at the end
I just can't figure the math of mixing them evenly
I'm using neopixel library
I can think of two ways of doing this.
One is to use the H channel of the HSV colour space (as I show in the answer to this question. This would give you a smooth transition between two colours through the pre-defined spectrum of the hue range.
The second is to simply specify two colours and then mix them at different percentages depending on how far along the length you are.
For example, here's a (untested) small function that "mixes" two individual colour channels together and returns the result:
uint8_t mix(uint8_t a, uint8_t b, int pct, int range) {
if (pct <= 0) return a;
if (pct >= range) return b;
return (((uint32_t)a * (range-pct)) / range) + (((uint32_t)b * pct) / range);
}
pct
is the led number in your chain, and range
is the total number of LEDs.
So you could (hypothetically):
uint8_t red1 = 0, green1 = 255, blue1 = 0;
uint8_t red2 = 255, green2 = 100, blue2 = 100;
for (int i = 0; i < 50; i++) {
uint8_t red = mix(red1, red2, i, 50);
uint8_t green = mix(green1, green2, i, 50);
uint8_t blue = mix(blue1, blue2, i, 50);
setLedColor(i, red, green, blue);
}
{}
button
50
in my example code is the number of LEDs. Obviously you need to tune that to the actual number of LEDs in your setup.