RSS

Tag Archives: wemos

Arduino colors!

Last night I was playing with a Neopixel Ring controlled by a Wemos Mini, when I decided to attach a potentiometer to manually handle the colors.
Now, when you read from an analog source you’ll get a value in an interval, like [0, 1024]. The problem with this kind of value is that it is a single number that needs to be mapped in three r,g,b values (ring.setPixelColor(n, red, green, blue);)!

After trying a good way to map [0,1024] => {[0,255], [0,255], [0,255]}, I remembered there are MANY ways to define colors: RGB, CMYC, HSV, …Wait! HSV? It’s perfect!
It’s like handling polar coordinates where you have an angle that describes the Hue and it is a number between 0 and 360. The other parameters are two vectors and describe the Saturation and the Brightness. These values can be set constant to 1, in my case.

First let’s map the analog value to a Hue value:

int val = analogRead(A0); // 0 - 1024
float h = 360.0 * ((float)val / (float)1024); // 0 - 360

then use this function to convert. Note that r,g and b are by ref.

/**
* HSV to RGB color conversion
* The hue value H runs from 0 to 360 degrees.
* The saturation S is the degree of strength or purity and is from 0 to 1. Purity is how much white is added to the color, so S=1 makes the purest color (no white).
* Brightness V also ranges from 0 to 1, where 0 is the black.
* R,G,B are between 0 and 255.
* http://www.cs.rit.edu/~ncs/color/t_convert.html
*/
void HSVtoRGB(float h, float s, float v, float *r, float *g, float *b)
{
    int i;
    float f, p, q, t;

    if (s == 0) {
        // achromatic (grey)
        *r = *g = *b = v;
    }
    else {
        h /= 60;      // sector 0 to 5
        i = floor(h);
        f = h - i;      // factorial part of h
        p = v * ( 1 - s );
        q = v * ( 1 - s * f );
        t = v * ( 1 - s * ( 1 - f ) );

        switch( i ) {
            case 0:
                *r = v;
                *g = t;
                *b = p;
                break;
            case 1:
                *r = q;
                *g = v;
                *b = p;
                break;
            case 2:
                *r = p;
                *g = v;
                *b = t;
                break;
            case 3:
                *r = p;
                *g = q;
                *b = v;
                break;
            case 4:
                *r = t;
                *g = p;
                *b = v;
                break;
            default:    // case 5:
                *r = v;
                *g = p;
                *b = q;
                break;
        }
        
        *r *= 255;
        *g *= 255;
        *b *= 255;
    }
}
 
Leave a comment

Posted by on 2017/03/24 in dev

 

Tags: ,