Skip to content

Instantly share code, notes, and snippets.

@R3tr0BoiDX
Forked from postspectacular/hsv2rgb.ino
Last active July 22, 2022 23:02
Show Gist options
  • Save R3tr0BoiDX/74466aca70d5dc9d15b9f8a310160019 to your computer and use it in GitHub Desktop.
Save R3tr0BoiDX/74466aca70d5dc9d15b9f8a310160019 to your computer and use it in GitHub Desktop.
C port of postspectacular's super compact HSV/RGB conversions for Arduino/C
float fract(float x) { return x - (int) x; }
float mix(float a, float b, float t) { return a + (b - a) * t; }
float step(float e, float x) { return x < e ? 0.0f : 1.0f; }
float constrain(float x, float low, float high) { return ((x) < (low) ? (low) : ((x) > (high) ? (high) : (x))); }
float min(float a, float b) { return (a > b) ? b : a; }
float* hsv2rgb(float h, float s, float b, float* rgb) {
rgb[0] = b * mix(1.0f, constrain(fabsf(fract(h + 1.0f) * 6.0f - 3.0f) - 1.0f, 0.0f, 1.0f), s);
rgb[1] = b * mix(1.0f, constrain(fabsf(fract(h + (float)2/3) * 6.0f - 3.0f) - 1.0f, 0.0f, 1.0f), s);
rgb[2] = b * mix(1.0f, constrain(fabsf(fract(h + (float)1/3) * 6.0f - 3.0f) - 1.0f, 0.0f, 1.0f), s);
}
float* rgb2hsv(float r, float g, float b, float* hsv) {
float s = step(b, g);
float px = mix(b, g, s);
float py = mix(g, b, s);
float pz = mix(-1.0f, 0.0f, s);
float pw = mix((float)2/3, -(float)1/3, s);
s = step(px, r);
float qx = mix(px, r, s);
float qz = mix(pw, pz, s);
float qw = mix(r, px, s);
float d = qx - min(qw, py);
hsv[0] = fabsf(qz + (qw - py) / (6.0f * d + 1e-10f));
hsv[1] = d / (qx + 1e-10f);
hsv[2] = qx;
}
int main(){
//Convert HSV to RGB
float hue = 1;
float sat = 1;
float val = 1;
float rgb[3];
hsv2rgb(hue, sat, val, rgb);
printf("Color as RGB is R: %f; G: %f, B: %f\n", rgb[0], rgb[1], rgb[2]);
//Convert from RGB back to HSV
float red = rgb[0];
float green = rgb[1];
float blue = rgb[2];
float hsv[3];
rgb2hsv(red, green, blue, hsv);
printf("Color as HSV is H: %f; S: %f, V: %f\n", hsv[0], hsv[1], hsv[2]);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment