15.1.2.3 NVMREG Erase of Program Memory
Before writing to program memory, the word(s) to be written must be erased or
previously unwritten. Program memory can only be erased one row at a time. No automatic
erase occurs upon the initiation of the write to program memory. To erase a program
memory row:
- Clear the NVMREGS bit to erase program memory locations, or set the NMVREGS bit to erase User ID locations.
- Write the desired address into the NVMADRH:NVMADRL register pair.
- Set the FREE and WREN bits.
- Perform the unlock sequence as described in the NVM Unlock Sequence section.
If the program memory address is write-protected, the WR
bit will be cleared and the erase operation will not take place.
While erasing program memory, the CPU operation is suspended and resumes when the operation is complete. Upon completion, the NVMIF bit is set, and an interrupt will occur if the NVMIE bit is also set.
Write latch data is not affected by erase operations, and WREN will remain unchanged.
Erasing One Row of Program Flash Memory
NVMCON1bits.NVMREGS = 0; // Point to PFM NVMADR = PFM_ADD; // 14-bit PFM address NVMCON1bits.FREE = 1; // Specify an erase operation NVMCON1bits.WREN = 1; // Enable write/erase cycle INTCONbits.GIE = 0; // Disable interrupts during unlock sequence //The next three steps are the required unlock sequence NVMCON2 = 0x55; // First unlock code NVMCON2 = 0xAA; // Second unlock code NVMCON1bits.WR = 1; // Initiate write/erase cycle INTCONbits.GIE = 1; // Enable interrupts NVMCON1bits.WREN = 1; // Disable writes