Fading Arduino RGB LED from one color to the other?

后端 未结 7 1869
攒了一身酷
攒了一身酷 2021-02-03 12:15

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

7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-03 12:38

    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]);
    }
    

提交回复
热议问题