adafruit / Adafruit_NeoPixel

Arduino library for controlling single-wire LED pixels (NeoPixel, WS2812, etc.)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add static method for converting RGB to HSV

TBog opened this issue · comments

commented

I was testing different animations and found that I needed to convert a RGB color to make a fade animation of it by changing the brightness.
There is no function to do this and because most code samples use hue as a float or unit8_t I couldn't copy-paste the solution.
I came up with this function:

void RgbToHsv(uint8_t r, uint8_t g, uint8_t b, uint16_t &h, uint8_t &s, uint8_t &v)
{
    uint8_t rgbMin, rgbMax;

    rgbMin = r < g ? (r < b ? r : b) : (g < b ? g : b);
    rgbMax = r > g ? (r > b ? r : b) : (g > b ? g : b);

    v = rgbMax;
    if (v == 0)
    {
        h = 0;
        s = 0;
        return;
    }

    s = 255 * static_cast<uint16_t>(rgbMax - rgbMin) / v;
    if (s == 0)
    {
        h = 0;
        return;
    }

    if (rgbMax == r)
        h = 65535 / 3 * 0 + 65535 / 6 * static_cast<int>(g - b) / (rgbMax - rgbMin);
    else if (rgbMax == g)
        h = 65535 / 3 * 1 + 65535 / 6 * static_cast<int>(b - r) / (rgbMax - rgbMin);
    else
        h = 65535 / 3 * 2 + 65535 / 6 * static_cast<int>(r - g) / (rgbMax - rgbMin);
}

Should I make a PR for this or just leave it here for anyone else that may need this functionality?

Make a PR for this. It would be a great addition to the library!