I tried to use self programming on the ATmega4809 (Nano Every). I have set BOOTEND to 1, and wrote a small program that fits into the BOOT section:
int main(void) { uint8_t *m; //_delay_ms(10); for (m=(uint8_t*) 0x6000; m<0xa000; m+=0x1000) { m[0]=0x34; _PROTECTED_WRITE_SPM(NVMCTRL.CTRLA, NVMCTRL_CMD_PAGEERASEWRITE_gc); while(NVMCTRL.STATUS & NVMCTRL_FBUSY_bm); } while(1); }
The strange thing is that the first page write always fails. When I dump the flash, I can see the following data in the application section:
3000: 34
4000: 34
5000: 34
When I uncomment the _delay_ms(), the program works as expected, and flash location 2000 is programmed as well. I tried different examples, in all cases, the first flash page write fails. I have figured out that the delay has to be 2msec or longer to make this work.
Any ideas what might be wrong?