1

I am calculating the current temperature to RGB related to a maximum temperature:

val = round(temp / tempMax * 255, 0);
if (val > 255) val = 255;

In maths the function is v=temp/tempMax*255. This works for a temperature between 0 and tempMax.

I want to do the same but in an area between minTemp and maxTemp-5. That means if the temp is exactly minTemp, val should be 0 and if it is maxTemp-5 it should be 255. all temperature that are lower than minTemp set val to zero and there will be special if statement for the area between maxTemp-5 and maxTemp. All the ifs are no problem but how do I need to modify my function that it calculating proportionally to the given borders?

T. Karter
  • 638
  • 7
  • 25

2 Answers2

1
val = round(((temp - minTemp) * 255) / ((maxTemp - 5) - minTemp), 0);
if (val < 0) val = 0;
else if (val > 255) val = 255;

You subtract minTemp from temp so that the range starts at zero. Then multiply by 255 / ((maxTemp - 5) - minTemp) to scale the range of minTemp -> maxTemp - 5 to 0 -> 255. Finally clamp the result to the allowable range.

I rearranged the formula to do the multiply first, so that it also works using integers. If you wanted it to work with unsigned numbers you could clamp to minTemp before applying the formula and remove the check for v < 0.

samgak
  • 23,944
  • 4
  • 60
  • 82
0
  1. RGB color of black body at some temperature

    is directly related to B-V index see:

    you have the equation t=f(B-V) in the OP just reverse it.

  2. what you asking is just linear interpolation

    simply:

    i=i0 + (t-t0)*(i1-i0)/(t1-t0)
    

    where t0,t1 is input temp range and i0,i1 is output intensity range.

Spektre
  • 49,595
  • 11
  • 110
  • 380