This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

write/read float value to flash

I try to write float values to flash memory of STM32F103RBT6.
but it cannot read the value and CPU reset by IWDT. my code is in below:

char str[100];
float Val;
float Data;
Data=123.456;

FLASH_Unlock();
FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
FLASH_ErasePage(0x08002000);
//write------------------------
        Val = *((unsigned long*)&Data);
        FLASH_ProgramWord(0x08002000,Val);
//Read-----------------------------
float *mem = (float *)0x08002000;
sprintf(str,"%f\n", *mem);
uart_out_str(str);


How ever the following code wires and reads integer values

u32 Data;
Data=123;
FLASH_Unlock();
FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
FLASH_ErasePage(0x08002000);
//write------------------------
FLASH_ProgramWord(0x08002000, Data);
//Read-----------------------------
u32 *mem = (u32 *)0x08002000;
sprintf(str,"%u\n", *mem);uart_out_str(str);

Parents
  • I modified the code a little bit as below and could write and read float values. In deed I write float values as unsigned int converted and read as well.

     unsigned int outVal;
    
     union
     {
     unsigned int i;
     float f;
     }var1,var2;
    
    var1.f=1231.2345;
    
    FLASH_Unlock();
    FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
    FLASH_ErasePage(0x0801FC00);
    //write------------------------
            outVal = *((unsigned int*)&var1.i);
            FLASH_ProgramWord(0x0801FC00,outVal);
    //Read-----------------------------
    u32 *mem = (u32 *)0x0801FC00;
    var2.i=*mem;
    sprintf(str,"%.2f\n", var2.f);uart_out_str(str);
    //-------
    FLASH_Lock();
    

Reply
  • I modified the code a little bit as below and could write and read float values. In deed I write float values as unsigned int converted and read as well.

     unsigned int outVal;
    
     union
     {
     unsigned int i;
     float f;
     }var1,var2;
    
    var1.f=1231.2345;
    
    FLASH_Unlock();
    FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
    FLASH_ErasePage(0x0801FC00);
    //write------------------------
            outVal = *((unsigned int*)&var1.i);
            FLASH_ProgramWord(0x0801FC00,outVal);
    //Read-----------------------------
    u32 *mem = (u32 *)0x0801FC00;
    var2.i=*mem;
    sprintf(str,"%.2f\n", var2.f);uart_out_str(str);
    //-------
    FLASH_Lock();
    

Children