So I am using an Atmega328p and a MCP9808 to take some i2c temp values. Im running it to my computer and viewing it in termial via USART.
Im getting the correct values for Celsius degrees (it shows 00022, which is around 71 degrees which is correct for my room).
However when I try to convert to fahrenheit I get values of 00054 which is def. not correct.
This is the formula im using:
float fahrenheitConvert(uint16_t celsius) {
float fahrenheit;
fahrenheit = celsius*(9/5) + 32;
return fahrenheit;
}
celsius is simply a uint16_t
value called "Temperature" in the main program (Which is what is printed out through serial just fine). Am I missing something? This seems like it should be a simple conversion?
9/5
is performed as truncating integer math, and evaluates to 1
(because 9/5
discarding fractional components is 1
). So your calculation is simplifying to:
fahrenheit = celsius * (1) + 32;
or just:
fahrenheit = celsius + 32;
which is obviously unhelpful.
To fix, change one of the literals to a double
literal so the math naturally converts to double
math:
fahrenheit = celsius * 9 / 5.0 + 32;
Now you use integer math to compute celsius * 9
, then implicitly coerce to double
when you divide by 5.0
, keeping the decimal component of the calculation.
Side-note: You don't actually need to separate this code into a declaration, an assignment, and a return
. The body of this function could simplify to just:
return celsius * 9 / 5.0 + 32;
and it would work equally well.