HSV to RGB color conversion in C, using integers only!
Jun0
My current goal is to build a mood lamp using a 3W RGB led and an AVR microcontroller. To control color fading I have taken a suggestion from promag who told me to explore the HSV color model because it deals with the colors in a much more natural and easy way.
I googled a little and found a conversion function from HSV to RGB written in C, the problem was that the algorithm was using floats and I can’t use them right now, as i’m using a ATtiny13 with only 1K of flash memory for the program. When the math lib is linked and floats are used the final program size increases a lot! So I had to convert the algorithm to use integers only. The other option was to change to a micro controller with more program memory.
The result of the conversion was the the following:
-
-
void HSVtoRGB( int *r, int *g,int *b, int h, int s, int v )
-
{
-
int f;
-
long p, q, t;
-
-
if( s == 0 )
-
{
-
*r = *g = *b = v;
-
return;
-
}
-
-
f = ((h%60)*255)/60;
-
h /= 60;
-
-
p = (v * (256 – s))/256;
-
q = (v * ( 256 – (s * f)/256 ))/256;
-
t = (v * ( 256 – (s * ( 256 – f ))/256))/256;
-
-
switch( h ) {
-
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:
-
*r = v;
-
*g = p;
-
*b = q;
-
break;
-
}
-
}
-
But while it works on a computer, when I use this code in a AVR, the color transitions are not smooth and there are a few glitches. I haven’t found the solution for that yet. Maybe that will be the content of my next post.
No Comments
No comments yet.
Leave a comment
You must be logged in to post a comment.