Hi Marco Coelho,
Thank you for your more detials, I can reproduce your problem on my side now.
1: Debug in step run s ramdomly
I think this is the KDS debug bug, I already report this problem to the KDS department, they will help to solve this KDS problem.
2: variable output "optimized out"
KDS engineer think this is not the bug, you can add volatile before the variable defination to solve it, eg, define temp1 as: volatile uint32_t temp1;
3: flash sector erase error: 0x20 in FTFA_FSTAT
I check your code, and test it carefully, at last I find it caused by the KDS option define problem, you need to delete all your old define symbol, and add it again, please configure it like this:


After the new configuration, then build it again, you will find your flash sector erase is ok.
You problem is caused by the define is invalid, then your flash clock will not correct, it will cause the flash operation error.
Attachment is my modified project, you can refer to it!
Wish it helps you!
If you still have question, please contact with me!
Have a great day,
(my name)
-----------------------------------------------------------------------------------------------------------------------
Note: If this post answers your question, please click the Correct Answer button. Thank you!
-----------------------------------------------------------------------------------------------------------------------