Maurice
I tried with your code and can confirm that it can't erase the Flash due to the stated error.
Your project is running core, bus and flash clocks at all 24MHz (in the code that you attached) and I don't think that it is clock related - I tried adjusting and didn't find any behavioral differences (it always failed).
Then I stepped the Flash erase code, which is OK (there is one "error" in trying to clear the read-only MGSTAT0 flag, but this probably won't actually hurt but instead just be redundant).
I can however tell you how to find the cause, which is probably somewhere in the initialistion (I am thinking about the flash not being accessible by a certain processor mode or similar but I didn't hunt where it was).
1. If you reset the board (stop in the debugger after the reset vector) and do the following you can see that the flash sector can be erased:
- Using the debugger write 0x09 to FTFA_FFCOB0, followed by
- write 0x04 to FTFA_FFCOB0
- write 0x80 to FTFA_FSTATE
Watch the FSTAT value remains at 0x80 (successful operation) [these three commands are actually all that is needed to delete your test sector]
2. Run to the point where your routine would start to do it and repeat. Now you see that it fails with 0xa0 (FSTAT), as the routine also fails.
3. Now repeat the simple test at various points during the initialisation (step through the code and decide when to check). Each time it is successful you can move on until you find where it starts failing. Then home in on the part of the initialisation which causes it until you see exactly what was modified to cause it to subsequently fail.
Once you know the cause you can then decide how best to work around it.
Note however that the code being used operates in Flash and can thus only work (on this processor) with addresses in the second half of the Flash (>= 0x40000). If you need to write/erase in areas lower than this you will need to either use a different module or execute the code in SRAM with interrupts disabled.
Regards
Mark