2013-05-28 3:58 AM
Hi,
I'm fairly new to the world of microcontrollers. I'm using the STM32F103ZG on the MCBSTM32E development board and am saving user-defined inputs to the BKP registers. Most inputs are positvie, small integers. However, I need to save a floating point input. The BKP write function in the STM library, BKP_WriteBackupRegister, is configured to accept uint16_t and I'm pretty sure it's not as simple as creating a copy of that routine and declaring the Data parameter to be float. What's the best way to save a float to a BKP register? Thanks in advance, Lisa2013-05-28 4:58 AM
float f=45;
uint16_t *x = ((uint16_t *)&f);
printf(''%04X %04
X'',x[0],x[1]);
2013-05-29 8:28 AM
Okay, I want to be sure I understand what I'm doing:
1. float f=123.45; -->Allocates 4 bytes in memory and stores 123.45 as float at address ''f''. f ---> 1110 0110 0110 0110 0100 0010 1111 0110 2. uint16_t *x = ((uint16_t *)&f); --> I create a pointer to an unsigned 2-byte integer and cast the float address as an unsigned 2-byte integer pointer so I can assign the address ''f'' to x. x[0] ----> 1110 0110 0110 0110 x[1] ----> 0100 0010 1111 0110 So, theoretically, I need to save x[0] to one BKP register and x[1] to another BKP register. Then, when I want to retrieve my float, I need to retrieve the ''integer'' data from the two BKP registers, put them back together and read the 4 bytes as a float. Is that right? Also, if the float value I'm trying to save is restricted to the interval [0,40] and one decimal place of accuracy, would there be any problem in doing this instead, for example: float userValue = 35.7; float f = userValue x 10; --------> 357 uint16_t saveToBKP = (uint16_t) f; Then when I retrieve it: float userValue = ((float)saveToBKP)/10; Thanks, Lisa2013-05-29 1:11 PM
Is that right?
Yes, pretty much.
float f=45;
uint16_t *x = ((uint16_t *)&f); /* Enable PWR and BKP clock */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); /* Enable write access to Backup domain */ PWR_BackupAccessCmd(ENABLE); printf(''%04X %04
X'',x[0],x[1]); BKP_WriteBackupRegister(BKP_DR1, x[0]); // Save BKP_WriteBackupRegister(BKP_DR2, x[1]); f = 0.0; // Trash x[0] = BKP_ReadBackupRegister(BKP_DR1); // Restore x[1] = BKP_ReadBackupRegister(BKP_DR2); printf(''%f
'', f); Also, if the float value I'm trying to save is restricted to the interval [0,40] and one decimal place of accuracy, would there be any problem in doing this instead, for example:
No problem, you can do as you wish provided you know the range/precision you wish to store.
2013-05-30 1:31 AM
Thanks Clive - very enlightening for me.