Fading Arduino RGB LED from one color to the other?

后端 未结 7 1868
攒了一身酷
攒了一身酷 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:43

    You can simplify your code by using a struct for your color.

    struct Color
    {
        unsigned char r;
        unsigned char g;
        unsigned char b;
    };
    

    Then, it is easy to have a fading function

    // the old color will be modified, hence it is not given as reference
    void fade(Color old, const Color& newColor)
    {
        // get the direction of increment first (count up or down)
        // each of the inc_x will be either 1 or -1
        char inc_r = (newColor.r - old.r)/abs(newColor.r-old.r); // note, that the right hand side will be sign extended to int according to the standard.
        char inc_g = (newColor.g - old.g)/abs(newColor.g-old.g);
        char inc_b = (newColor.g - old.g)/abs(newColor.g-old.g);
    
        fadeOneColor(old.r, newColor.r, inc_r, old);
        fadeOneColor(old.g, newColor.g, inc_g, old);
        fadeOneColor(old.b, newColor.b, inc_b, old);
    }
    
    void fadeOneColor( unsigned char& col_old, 
                       const unsigned char& col_new, 
                       const char inc, 
                       Color& col)
    {
        while(col_old != col_new)
        {
            col_old += inc;
            SetColor(col); 
            delay(20);
        }        
    }
    

提交回复
热议问题