Skip to content

Commit 97f58ff

Browse files
matthijskooijmanfpistm
authored andcommitted
Document noinit section
1 parent 2d43e76 commit 97f58ff

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

API.md

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
* [I2C](https://github.com/stm32duino/wiki/wiki/API#i2C)
1313
* [CMSIS DSP](https://github.com/stm32duino/wiki/wiki/API#cmsis-dsp)
1414
* [EEPROM emulation](https://github.com/stm32duino/wiki/wiki/API#EEPROM-Emulation)
15-
15+
* [Other](https://github.com/stm32duino/wiki/wiki/API#other)
16+
* [Remembering variables across resets](https://github.com/stm32duino/wiki/wiki/API#Remembering-variables-across-resets)
1617
# Core
1718

1819
This part describes the STM32 core functions.
@@ -584,4 +585,33 @@ Default last sector used correspond to default board configuration.
584585
585586
For example, NUCLEO_F767ZI is by default configured in single bank. Last sector correspond to this bank configuration.
586587
If this configuration is changed, it is then mandatory to customize `FLASH_BASE_ADDRESS`/`FLASH_DATA_SECTOR`,
587-
even to use last sector of Flash.
588+
even to use last sector of Flash.
589+
590+
# Other
591+
592+
## Remembering variables across resets
593+
Since core version 1.9.0 (see [PR #996](https://github.com/stm32duino/Arduino_Core_STM32/pull/996)), it is possible to mark variables as "noinit", which prevents them from being initialized to a fixed value at startup. This allows using these variables to remember a value across resets (since the reset itself leaves memory unchanged, it is only the startup code that normally resets all variable values, but that is prevented by noinit).
594+
595+
To do this, the variable must be placed in the `.noinit` section by adding `__attribute__((__section__(".noinit")))` (this is exactly the same as how this works on the original Arduino AVR core). Typically, you would also need to check the startup reason register so you can initialize the variable with a default on the first startup. For example, something like:
596+
597+
```
598+
unsigned boot_count __attribute__((__section__(".noinit")));
599+
600+
void setup() {
601+
Serial.begin(115200);
602+
while (!Serial); // Wait for serial port open
603+
604+
// Initialize the variable only on first power-on reset
605+
if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST))
606+
boot_count = 1;
607+
__HAL_RCC_CLEAR_RESET_FLAGS();
608+
609+
Serial.print("Boot number: ");
610+
Serial.println(boot_count);
611+
++boot_count;
612+
}
613+
614+
void loop() { }
615+
```
616+
617+
This shows the number of boots since the last POR by incrementing a noinit variable across resets. Note that when you first upload this, it might not start at 1 but at some arbitrary value, because typically the first boot after an upload is not a power-on-reset. To start at 1, disconnect and reconnect power.

0 commit comments

Comments
 (0)