Foreword
It has long been no secret to anyone that STMicroelectronics produces wonderful 32-bit ARM STM32 microcontrollers. Recently, they are gaining more and more popularity, and for good reason, which I do not intend to repeat in this article. Who cares -
one ,
two and
three .
However, a sharp increase in popularity has some unpleasant drawbacks - quite often the authors of articles repeat the same mistakes. And if the right moment is described superficially in the official document of the manufacturer, then the devil will break his leg until he finds a solution to the problem.
It is about this moment that I want to tell. Namely - how to properly use the ability to write to the built-in flash of our MK. Welcome under cat.
')
We smoke mana, we read articles
The overwhelming majority of
articles (and more precisely, in general, all that I have seen) offer an implementation of the algorithm recommended in the
official flash programming
manual . Here is this:

Code, compile, check - everything works. It works well. Exactly until you turn on optimization. I use gcc and checked with the -O1 and -O2 keys. Without optimization - it works. With optimization - does not work. We nervously smoke, drink coffee, and spend a day or two searching for problems and thinking about the impermanence of life.
How to
I do not know why the manufacturer advises to use an incorrectly working algorithm. Perhaps somewhere this is explained, but in two days I did not manage to find anything. The solution turned out to be quite simple - in the FLASH-> SR register, in order to control the end of the operation, it is necessary to use not the BSY bit (sincerely I don’t understand why even ST recommends using it), but the EOP bit set when the current erase / write operation ends.
The reason is simple - for one reason or another, at the time of checking the BSY bit may not yet be set. However, the EOP bit is set if and only when the operation is completed. This bit is reset manually by writing one to it. Kodim, check, enjoy life.
Raw
For completeness, you need to find and read other articles on this topic (link to one of them is given above). Here I also attach the source code with a brief description.
Unlocking work with flash - these two lines must be inserted into the initialization function of the MC:
FLASH->KEYR = 0x45670123; FLASH->KEYR = 0xCDEF89AB;
Erasing flash page - before recording, you need to erase the data at the desired addresses, this is a flash feature:
Record:
These are the pies. Enjoy all the coding and fewer bugs.