enter image description here

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);
  • Very clever However, only one LED lights up, sorry I can't debug it myself :<
    – Shiba-inu
    May 11 '20 at 3:12
  • My sketch: pastebin.com/0fYD6w3y
    – Shiba-inu
    May 11 '20 at 3:26
  • the sketch belongs in your question as text, not as a link ... please edit your question ... format the code properly using the {} button
    – jsotola
    May 11 '20 at 5:33
  • The 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.
    – Majenko
    May 11 '20 at 9:39
  • I tried both 8 leds and 50 and 7 counting from 0 but i think that even with more leds in sketch more than 1 led would light up
    – Shiba-inu
    May 11 '20 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.