cancel
Showing results for 
Search instead for 
Did you mean: 

Wrong calculations when using floating point variables. (STM32F407)

MSavo.1
Associate

I realised there was such a problem, when I was trying to convert ADC temperature sensor data to degrees in Celsius. After many hours of trying to find a formula that works I found this one from the repository examples:

ADCxConvertedData_Temperature = (((ADC_Data - 0.76)/(TS_CAL2 - TS_CAL1)) + 25);

So far so good, but when I run the code I get values around 27 - 28 degrees, which is not impossible, but seems too high for it to be room temperature, so I wrote another formula which seems to be also accurate for temperature conversion:

temp = (uADC_DR_val[6] / ((TS_CAL2 / 110 + TS_CAL1 /30)/2));

But with this one I also get values from 26 to 28 degrees.

So I decided to try and calculate these formulas with pen and paper using the ADC value that the MCU got and it turns out, I got lower numbers as a result. For example, using the first formula, where ADC_Data = 585, according to my calculations I get a result of 25.27 degrees, but my code calculates the same formula as 27.204.

I also saw that even when I use int variables I don't always get the number rounded correctly. Sometimes it rounds 26.3 to 27 and sometimes it rounds 27.7 to 27.

My question is, is it possible, that I don't have the FPU set up correctly (I checked and the FPU is enabled both in the MCU settings and in the CubeMX FreeRTOS settings) or could there be a problem with the hardware and that's why it is acting so weird?

I am using a custom board with STM32F407 MPU.

PS. I also get a HardFault when trying to do three or more floating point operations, which reads to be Bad Address Read.

1 REPLY 1
S.Ma
Principal

First, the measured temperature is the silicon chip wrapped in plastic package, so temperaturr maybe higher than ambiant.

Second, the calibrated values in flash are at probably 3.0V. If your chip is not 3.0V, you need Vref measurement to compensate for it.

Third, float can be avoided as it drags math lib to memory space. Maybr the.closest Nucleo board cube sw package has ADC example with what you need. Good.luck! Try chatGPT in case it brings clues within a minute to reduce wait if in a hurry.