24.12 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 the programming sequence is initiated. The instruction Word at the physical location pointed to by the NVMADDR register is, then, programmed. Programming occurs on 32-bit Word boundaries; therefore, bits ‘0’ and ‘1’ of the NVMADDR register are ignored.

When a Word is programmed, it must be erased before it can be programmed again, even if changing a bit from an erased ‘1’ state to a ‘0’ state.

Word programming will only succeed if the target address is in a page that is not write-protected. Programming to a write-protected PFM page will fail and result in the WRERR bit being set in the NVMCON register. Programming a write-protected BFM page will fail but does not set the WRERR bit.

A programming sequence consists of the following steps:

  1. Write 32-bit data to be programmed to the NVMDATA0 register.
  2. Load the NVMADDR register with the address to be programmed.
  3. Set the WREN bit = 1 and NVMOP bits = 1 in the NVMCON register. This defines and enables the programming operation.
  4. Initiate the programming operation. (See NVMKEY Register Unlocking Sequence from Related Links.)
  5. Monitor the WR bit of the NVMCON register to flag completion of the operation.
  6. Clear the WREN bit in the NVMCON register.
  7. 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
    }
…