I want to store some float data in the FRAM register of my TI MSP430 microcontroller and have some prolems.
I don't know how I can do this.
With normal integer variables it is no problem.
Normal integer variables:
void main()
{
uint32_t value = 25;
uint32_t framPtr = 0xD000;
FRAMC_write_uint32_t(value, (uint32_t*)framPtr);
}
void FRAMC_write_uint32_t(uint32_t value,
uint32_t *framPtr)
{
*framPtr = value;
}
But with float values it doesn't work. I tried to change the value inside the function to float, but no result.
This is my float data:
float value = 1.25;
uint32_t framPtr = 0xD000;
With this function it doesn't work:
void FRAM_write_float(float value,
uint32_t *framPtr)
{
*framPtr++ = (float)value;
}
It saved the data 1.40129846e-45 (DEN) (HEX: 0x00000001) in my memory bank.
I hope somebody can help me with my problem. Thanks!
The simplest approach to reinterpret the bits would be to use memcpy
, if you know that sizeof(float) == sizeof(uint32_t)
1
float f = /* some_val */;
uint32_t fbits = 0;
memcpy(&fbits, &f, sizeof fbits);
Should be safe enough, since unsigned integers don't usually have trap values.
If your compiler supports C99 and onward. You can also do type punning via a union.
union {
float from;
uint32_t to;
} pun = { .from = /*some val*/ };
// use pun.to
The above doesn't actually copy anything, so may be marginally faster in a tight loop. (And as Olaf points out, this is the standard compliant way for modern C).
1: If your compiler supports it, you should probably _Static_assert
on it.