Now we'll add some common utility functions that can be used by any of the patterns:

First we have the Red(), Blue() and Green() functions.  These are the inverse of the Neopixel Color() function.  They allow us to extract the Red, Blue and Green components of a pixel color.

    // Returns the Red component of a 32-bit color
    uint8_t Red(uint32_t color)
    {
        return (color >> 16) & 0xFF;
    }

    // Returns the Green component of a 32-bit color
    uint8_t Green(uint32_t color)
    {
        return (color >> 8) & 0xFF;
    }

    // Returns the Blue component of a 32-bit color
    uint8_t Blue(uint32_t color)
    {
        return color & 0xFF;
    }

The DimColor() funtion uses Red(), Green() and Blue() to pull apart a color and re-construct a dimmed version of it.  It shifts the red, green and blue components of the pixel color one bit to the right - effectively dividing by 2.  Since red, green ane blue are 8-bit values, they will fade to black after the 8th call at the latest.

This function is used to create the fading tail effect in the Scanner pattern.

// Return color, dimmed by 75% (used by scanner)
    uint32_t DimColor(uint32_t color)
    {
        uint32_t dimColor = Color(Red(color) >> 1, Green(color) >> 1, Blue(color) >> 1);
        return dimColor;
    }

Next we have the Wheel() function as used by the RainbowCycle pattern.  This is borrowed pretty much as-is from the StrandTest example.

// Input a value 0 to 255 to get a color value.
    // The colours are a transition r - g - b - back to r.
    uint32_t Wheel(byte WheelPos)
    {
        WheelPos = 255 - WheelPos;
        if(WheelPos < 85)
        {
            return Color(255 - WheelPos * 3, 0, WheelPos * 3);
        }
        else if(WheelPos < 170)
        {
            WheelPos -= 85;
            return Color(0, WheelPos * 3, 255 - WheelPos * 3);
        }
        else
        {
            WheelPos -= 170;
            return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
        }
    }

The Reverse() function will reverse the direction of pattern execution.

    // Reverse direction of the pattern
    void Reverse()
    {
        if (Direction == FORWARD)
        {
            Direction = REVERSE;
            Index = TotalSteps-1;
        }
        else
        {
            Direction = FORWARD;
            Index = 0;
        }
    }

And finally, we have the ColorSet() function to set all pixels to the same color synchronously.  This is used by the Fader pattern.

    // Set all pixels to a color (synchronously)
    void ColorSet(uint32_t color)
    {
        for (int i = 0; i < numPixels(); i++)
        {
            setPixelColor(i, color);
        }
        show();
    }

This guide was first published on Mar 02, 2015. It was last updated on Mar 02, 2015.

This page (Common Utility Functions) was last updated on Dec 04, 2021.

Text editor powered by tinymce.