I\'ve currently managed to get my LED to cycle through eight colors that I\'ve selected. Everything is working correctly, except that I want to go for a more natural feel, and w
Here's a fast linear fade between two RGB values stored in uint32_t
as 0x00RRGGBB
as is used in many addressable RGB pixel strips such as in NeoPixel (and is inspired by some of the code in the NeoPixel Arduino library).
It doesn't take colour space into consideration but still looks nice and smooth in practice.
uint32_t fadeColor(uint32_t const x, uint32_t const y, uint8_t const fade)
{
// boundary cases don't work with bitwise stuff below
if (fade == 0)
{
return x;
}
else if (fade == 255)
{
return y;
}
uint16_t const invFadeMod = (255 - fade) + 1;
uint16_t const fadeMod = fade + 1;
// overflows below to give right result in significant byte
uint8_t const xx[3] // r g b
{
static_cast((uint8_t(x >> 16) * invFadeMod) >> 8),
static_cast((uint8_t(x >> 8) * invFadeMod) >> 8),
static_cast((uint8_t(x >> 0) * invFadeMod) >> 8),
};
uint8_t const yy[3] // r g b
{
static_cast((uint8_t(y >> 16) * fadeMod) >> 8),
static_cast((uint8_t(y >> 8)* fadeMod) >> 8),
static_cast((uint8_t(y >> 0)* fadeMod) >> 8),
};
return ((uint32_t)(xx[0] + yy[0]) << 16) | ((uint32_t)(xx[1] + yy[1]) << 8) | (xx[2] + yy[2]);
}