Skip to main content
KE.1
Associate
Feb 23, 2021 5:03 PM UTC
Solved

how to retain global variable after NVIC_reset() in STM32F302R8

Hi Team,

I want to retain a value of variable after software reset

i tried __no_init but variable was resetting to zero

Is there any way i can write into Flash during runtime and fetch it back after reset

Thanks,

Krupashankar

This topic has been closed for replies.
KnarfB
KnarfBBest answer
Super User
Feb 23, 2021 6:26 PM UTC

It works with gcc like this:

in .c:

int no_init __attribute__ ((section (".no_init")));

in linker description file .ld add a section before heap+stack:

.no_init :
 {
 *(.no_init)
 } > RAM

For testing:

printf("no_init: %d\n", no_init );
 	no_init++;
 
	HAL_Delay(100);
	NVIC_SystemReset();

Redirect printf to an UART or such and watch no_init variable being incremented after each reset.

hth

KnarfB

3 replies

Tesla DeLorean
Guru
Feb 23, 2021 5:53 PM UTC

The processor doesn't clear the memory.

Check what your startup.s code is doing, and perhaps shrink the memory visible to the linker if you need to place it outside that scope.

Yes you can write data into FLASH, there are examples in the HAL trees for assorted boards. Memory will need to be erased prior to writing, so often better to journal the variable, or structure holding retained data, across the flash page/sector.

Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..
KnarfB
KnarfBBest answer
Super User
Feb 23, 2021 6:26 PM UTC

It works with gcc like this:

in .c:

int no_init __attribute__ ((section (".no_init")));

in linker description file .ld add a section before heap+stack:

.no_init :
 {
 *(.no_init)
 } > RAM

For testing:

printf("no_init: %d\n", no_init );
 	no_init++;
 
	HAL_Delay(100);
	NVIC_SystemReset();

Redirect printf to an UART or such and watch no_init variable being incremented after each reset.

hth

KnarfB

KE.1
KE.1Author
Associate
Mar 3, 2021 4:14 AM UTC

Thank you:smiling_face_with_smiling_eyes: