Write variables to flash during upload on STM32


I have a question regarding custom upload options:

I’d like to have different serial numbers on my devices which should be located at a specific flash location on my STM32L device (e.g. max_flash_addr - 2KB or similar). These values can be later read when the program is running.

What may be a good way to achieve this?

Thank you

The question is very similiar to How to reserve a page of Flash memory? (STM32/arduino). An example project for that was located at GitHub - maxgerhardt/pio-stm32-reserved-flash-sector: An example for a modified linker script that relocates the code so that a 16kBytey page becomes free.. With this you can prevent the firmware from taking up a certain space (e.g., the last kilobyte or flash sector).

With OpenOCD commands (program with a specific address and .bin file of arbitrary content) you can then write to these addresses. For this you can create a custom target that triggers this write, or implement a fully custom upload method that flashes both firmware and some custom binary blob (Redirecting...).

Hi Max,

thank you very much for your links and suggestions. I was thinking about the following approach:

  • writing a extra_script.py to manage the upload and
  • using the ST-Link command line utility to upload to the STM board using the -w32 to write to flash memory as mentioned here in the manual:

What do you think?

PlatformIO doesn’t have the STM32CubeProgrammerCLI as a package, so you will have to do manual work to get that in the PlatformIO system. The easiest way is to use the already existing OpenOCD package. That’s the most direct and portable way.

Thanks again, Max.

I read through all the material you posted and modifying the linker script seems valid way to make sure a certain area at the end of the flash memory is reservered.

You’re right, it makes sense to use an modified OpenOCD upload. I’m just not 100% sure where to start. Which Platformio script controls the upload process and how can I substitute that script to make OpenOCD write variables into the flash on upload?

You don’t need to modify PlatformIO-internal scripts, you tell PlatformIO to use your custom upload logic. I’ve already linked that above with

The reference logic for a regular OpenOCD upload is here and here.