2

I'm trying to receive a float number through a VCP and writing it in the Flash memory of the STM32F4 discovery board, using Keil IDE. The functions used to write in the Flash memory:

FLASH_Status FLASH_ProgramDoubleWord(uint32_t Address, uint64_t Data);
FLASH_Status FLASH_ProgramWord(uint32_t Address, uint32_t Data);
FLASH_Status FLASH_ProgramHalfWord(uint32_t Address, uint16_t Data);
FLASH_Status FLASH_ProgramByte(uint32_t Address, uint8_t Data);

accept an unsigned integer value as data input, but I've managed to write a signed integer in the Flash memory using this code:

int dataflash1 = -1000;
int gain;
uint32_t Address= 0x08008000;
.......
FLASH_ProgramWord(Address,dataflash1);
.......
gain=*(int*)Address;

I still haven't managed to write a float data, though. If I change "int" with "float" (they should both be 4 bytes data, it's said in the keil compiler guide) I get numbers like 1.7345673 e-42.

Maybe it's a dumb question, but if you could give me a clue I'd really appreciate.

Blueberry
  • 29
  • 1
  • 5
  • Do you mean that you changed `gain = *(int*)Address` to `gain = *(float*)Address`? Did you also change `int gain;` to `float gain;`? – swineone Jul 11 '14 at 02:03

2 Answers2

5

Writing data as float:

float f = 12.34;
FLASH_ProgramWord(Address, *(uint32_t *)&f);

Converting read data to float:

uint32_t u = flash_read(Address);
float f = *(float *)&u;
Kibernetik
  • 2,947
  • 28
  • 35
  • This works well, but it generates a warning: `warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]` – meetpatelvgec Jan 24 '23 at 14:42
1

I don't see why this shouldn't work:

float dataflash1 = -1000.0f;
float gain;
uint32_t Address= 0x08008000;
.......
FLASH_ProgramWord(Address,dataflash1);
.......
gain=*(float*)Address;

Note that you need to declare both dataflash1 and gain as float. The representation of any given number (for instance, -1000) as an integer and a floating point number is, in general, completely different, so it's unreasonable to expect that you could write data using its integer representation to memory and then read it back directly to a floating point number. You need to change the bit-level representation first. Nothing here is specific about writing to flash: the following code, using variables in RAM only, won't work either:

int dataflash1 = -1000;
float gain;
gain=*(float*)Address;

Should you try to print the value of gain, I can assure you the result won't be -1000.

swineone
  • 2,296
  • 1
  • 18
  • 32