I read 16 Bit two's complement sensor data byte after byte via I2C with a STM32, so I have to stick the High- and Low-Byte back together and convert this number to a float to get the real value.
My expression in C for this is
// Convert temperature value (256 LSBs/°C with +25°C Offset)
float temp = (tmpData[1] << 8 | tmpData[0])/256.0 + 25.0;
When I use the debugger of the STM32CubeIDE to check the calculation, the expression shows the correct conversion of the data (see screenshot). But the value assigned to the temp variable is always 25! It seems to me like the first term of the expression is always assumed to be 0 or something? I already tried a direct cast of the term in brackets to float, but that does not change anything.
Can anybody point me to the problem? Why is the debugger showing the correct value, but the code is assigning a wrong one?
The expressions in the screenshots below are captured by howering the mouse over the corresponding part of the above code line in debug mode.
Fig. 1: Complete expression of calculation (gives result as expected)
Fig. 2: tmpData content (original two Bytes)
Fig. 3: Result of byte shifting and sticking
Fig. 4: temp result (always 25, even when expression above showes the expected value)
temp is only a volatile for the moment, because I don't use that value yet and the compiler optimizes it out.
OK, new morning, new intuition...
The problem wasn't with this code line from the question, but (typ. Murphy) with the stuff I did not post. The I2C is read via DMA to the array and at the point I wanted to do the conversion the peripheral was not done yet. That's why the array elements were always empty when the code accessed them, but at the time I checked the values in the debugger the I2C peripheral had finished the transmission and I saw the expected values.
So the solution is to check if the peripheral is still busy...