STM32: How to Write a float to a Backup Register.

I have been asked several times how to write a float variable to external EEPROM or to backup registers. I found this question interesting, so I decided to answer it in an article.

As you know, on STM32 one backup register holds 16 bits, while a float variable contains 32 bits. So to store one float variable, we need 2 backup registers.

The first thing that comes to mind is to do it like this.

float f;

BKP->DR1 = f;//store the lower 16 bits
BKP->DR2 = f>>16;//store the upper 16 bits


STM32: How to Write a float to a Backup Register.

But the compiler complains about this code, saying that the shift operation cannot be applied to a float variable.

Since that doesn't work, let's use everyone's favorite pointers.

float f;
uint16_t* tmp;

tmp = (uint16_t*) &f;
BKP->DR1 = *tmp;
BKP->DR2 = *(tmp+1);

And this code works perfectly.

The float variable is reassembled, again using a pointer.

uint32_t value;
float f;
	
value = (BKP->DR2<<16 | BKP->DR1);
f = *(float*)&value;


Here again the question arises: why can't we simply cast to float?

f = (float)value;//this will not work

Why do we have to cast to a float pointer and only then dereference it?

The point is that a simple type cast either adds zeros or cuts off extra digits!!!!

uint8_t->uint32_t//adds zeros 
uint32_t->uint8_t//cuts off extra digits

Whereas casting to a pointer type tells the compiler how to interpret the data at the given address.