我们在做RGB灯光控制时,经常需要实现一种光线柔和渐变的过程.简单的都是用RGB三原色变化,但这种效果差强人意.通过HSV颜色模型则可以实现非常好的渐变效果.这里贴出主要实现代码.
#include <math.h>
#define MAX(a, b) (a > b ? a : b)
#define MIN(a, b) (a < b ? a : b)
/* HSV2RGB:
* Converts from HSV colorspace to RGB values.
* HSV2RGB(iHSV_H / 3.0, 1, 1, &r, &g, &b);
*/
void HSV2RGB(float h, float s, float v, int *r, int *g, int *b)
{
float f, x, y, z;
int i;
v *= 255.0;
if (s == 0.0) {
*r = *g = *b = (int)v;
} else {
while (h < 0)
h += 360;
h = fmod(h, 360) / 60.0;
i = (int)h;
f = h - i;
x = v * (1.0 - s);
y = v * (1.0 - (s * f));
z = v * (1.0 - (s * (1.0 - f)));
switch (i) {
case 0: *r = v; *g = z; *b = x; break;
case 1: *r = y; *g = v; *b = x; break;
case 2: *r = x; *g = v; *b = z; break;
case 3: *r = x; *g = y; *b = v; break;
case 4: *r = z; *g = x; *b = v; break;
case 5: *r = v; *g = x; *b = y; break;
}
}
}
使用方法,要主循环中加下以下代码:
if (g_iWRGBApply == 1) { // 渐变模式开关,计算完后,在定时器中进行调光
g_iWRGBApply = 0;
g_iWRGBSeed++; // 颜色种子,0~360之间循环
if (g_iWRGBSeed >= 360)
g_iWRGBSeed = 0;
HSV2RGB(g_iWRGBSeed, 1.0, 1.0, &g_iRed, &g_iGreen, &g_iBlue); // HSV模型转成RGB三原色
}
功能已在STM8的量产产品上实现,效果非常不错.