15.13 Word Programming
The smallest block of data that can be programmed in a single operation is one Flash write Word (32-bit). The data to be programmed must be written to the NVMDATA0 register, and the address of the Word must be loaded into the NVMADDR register before initiating the programming sequence. The instruction Word at the physical location pointed to by the NVMADDR register is, then, programmed. Programming occurs on 32-bit Word boundaries; therefore, the user can ignore the bits ‘0
’ and ‘1
’ of the NVMADDR register.
If programming a Word, erase it before programming again, even if changing a bit from an erased ‘1
’ state to a ‘0
’ state.
Word programming only succeeds if the target address is in a page that is not write-protected. Programming to a write-protected PFM page fails and results in the WRERR bit being set in the NVMCON register. Programming a write-protected BFM page fails but does not set the WRERR bit.
A programming sequence consists of the following steps:
- Write 32-bit data to be programmed to the NVMDATA0 register.
- Load the NVMADDR register with the address to be programmed.
- Set the WREN bit =
1
and NVMOP bits =1
in the NVMCON register. This defines and enables the programming operation. - Initiate the programming operation. (See NVMKEY Register Unlocking Sequence from Related Links.)
- Monitor the WR bit of the NVMCON register to flag completion of the operation.
- Clear the WREN bit in the NVMCON register.
- Check for errors and process accordingly.
The following code shows code for Word programming, where a value of 0x12345678 is programmed into location 0x1008000.
Word Programming Code Example:
…
// Set up Address and Data Registers
NVMADDR= 0x1008000; // physical address
NVMDATA0 = 0x12345678; // value
// set the operation, assumes WREN = 0
NVMCONbits.NVMOP = 0x1; // NVMOP for Word programming
// Enable Flash for write operation and set the NVMOP
NVMCONbits.WREN = 1;
// Start programming
NVMInitiateOperation(); // see Initiate NVM Operation (Unlock Sequence Example)
// Wait for WR bit to clear
while (NVMCONbits.WR);
// Disable future Flash Write/Erase operations
NVMCONbits.WREN = 0;
// Check Error Status
if(NVMCON & 0x3000) // mask for WRERR and LVDERR
{
// process errors
}
…