This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Calculation for temperature false

In the data sheet of SHT21 is this the formula to calculate the temperature:

T = -46.85 + 175.72 * temp_data / 2^16

temp_data has the value 26'464.

The result should be: T = 24.1°C

But in my code I get this result = 18052.3105

Code:

float temperature;

temperature = (-46.85 + (175.72*(temperature_data / 65536)));

What is wrong with my calculation for the temperature?

Parents
  • Hi. I guess you have declared the variable temperature_data as an Int? You will need to cast it to a float like this:

    temperature = (-46.85 + (175.72*( (float) temperature_data / 65536)));
    

    This is because if you don't do the casting the '/' operator (correctly) assumes that both values are integers and that you want integer as result as well. If (at least) one of the variables is of type float (or double) the compiler will produce a float as a result instead. A bit more detailed answer here.

Reply
  • Hi. I guess you have declared the variable temperature_data as an Int? You will need to cast it to a float like this:

    temperature = (-46.85 + (175.72*( (float) temperature_data / 65536)));
    

    This is because if you don't do the casting the '/' operator (correctly) assumes that both values are integers and that you want integer as result as well. If (at least) one of the variables is of type float (or double) the compiler will produce a float as a result instead. A bit more detailed answer here.

Children
No Data
Related