Datasheet

30. Self-Programming the Flash
30.1 Overview
In ATmega48PA, there is no Read-While-Write support and no separate boot loader section. The SPM
instruction can be executed from the entire Flash.
The device provides a self-programming mechanism for downloading and uploading program code by the
MCU itself. The self-programming can use any available data interface and associated protocol to read
code and write (program) that code into the program memory.
The program memory is updated in a page by page fashion. Before programming a page with the data
stored in the temporary page buffer, the page must be erased. The temporary page buffer is filled with
one word at a time using SPM, and the buffer can be filled either before the page erase command or
between a page erase and a page write operation:
Alternative 1, fill the buffer before a Page Erase
Fill temporary page buffer
Perform a page erase
Perform a page write
Alternative 2, fill the buffer after Page Erase
Perform a page erase
Fill temporary page buffer
Perform a page write
If only a part of the page needs to be changed, the rest of the page must be stored (for example in the
temporary page buffer) before the erase, and then be re-written. When using alternative 1, the boot
loader provides an effective Read-Modify-Write feature which allows the user software to first read the
page, do the necessary changes, and then write back the modified data. If alternative 2 is used, it is not
possible to read the old data while loading since the page is already erased. The temporary page buffer
can be accessed in a random sequence. It is essential that the page address used in both the page erase
and page write operation is addressing the same page.
30.1.1 Performing Page Erase by Store Program Memory (SPM)
To execute page erase, set up the address in the Z-pointer (R30 and R31), write “0x00000011” to Store
Program Memory Control and Status Register (SPMCSR) and execute Store Program Memory (SPM)
within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must
be written to PCPAGE ([Z12:Z6]) in the Z-register. Other bits in the Z-pointer will be ignored during this
operation.
The CPU is halted during the page erase operation
Note:  If an interrupt occurs in the time sequence the four cycle access cannot be guaranteed. In
order to ensure atomic operation you should disable interrupts before writing to SPMCSR.
30.1.2 Filling the Temporary Buffer (Page Loading)
To write an instruction word, set up the address in the Z-pointer (R30 and R31) and data in R1:R0, write
“0x00000001” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The content
of PCWORD ([Z5:Z1]) in the Z-register is used to address the data in the temporary buffer. The temporary
ATmega48PA/88PA/168PA
Self-Programming the Flash
© 2018 Microchip Technology Inc.
Datasheet Complete
DS40002011A-page 337