HSV to RGB color conversion in C, using integers only!

15
Jun
0

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:

  1.  
  2. void HSVtoRGB( int  *r, int *g,int *b, int h, int s, int v )
  3. {
  4.         int f;
  5.         long p, q, t;
  6.  
  7.         if( s == 0 )
  8.         {
  9.                 *r = *g = *b = v;
  10.                 return;
  11.         }
  12.  
  13.         f = ((h%60)*255)/60;
  14.         h /= 60;
  15.  
  16.         p = (v * (256 – s))/256;
  17.         q = (v * ( 256(s * f)/256 ))/256;
  18.         t = (v * ( 256(s * ( 256 – f ))/256))/256;
  19.  
  20.         switch( h ) {
  21.                 case 0:
  22.                         *r = v;
  23.                         *g = t;
  24.                         *b = p;
  25.                         break;
  26.                 case 1:
  27.                         *r = q;
  28.                         *g = v;
  29.                         *b = p;
  30.                         break;
  31.                 case 2:
  32.                         *r = p;
  33.                         *g = v;
  34.                         *b = t;
  35.                         break;
  36.                 case 3:
  37.                         *r = p;
  38.                         *g = q;
  39.                         *b = v;
  40.                         break;
  41.                 case 4:
  42.                         *r = t;
  43.                         *g = p;
  44.                         *b = v;
  45.                         break;
  46.                 default:
  47.                         *r = v;
  48.                         *g = p;
  49.                         *b = q;
  50.                         break;
  51.         }
  52. }
  53.  

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.

Filed under: Photography
No Comments

No Comments

No comments yet.

Leave a comment

You must be logged in to post a comment.