12.1.2 NVM Unlock Sequence

The unlock sequence is a mechanism that protects the NVM from unintended self-write programming, sector reads, and erasing. The sequence must be executed and completed without interruption to successfully complete any of the following operations:

  • PFM sector erase
  • PFM sector write from holding registers
  • PFM sector read into write block holding registers
  • PFM word write directly to NVM
  • DFM byte write directly to NVM
  • Write to Configuration Words
Each of these operations correspond to one of four unlock code sequences as shown in the following table:
Table 12-4. NVM Unlock Codes
Operation First Unlock Byte Second Unlock Byte

NVMCON1
Operation Bit

Word/Byte write 55h AAh WR
Sector write DDh 22h SECWR
Sector erase CCh 33h SECER
Sector read BBh 44h SECRD

The general unlock sequence consists of the following steps and must be completed in order:

  • Write first unlock byte to NVMCON2
  • Write second unlock byte to NMVCON2
  • Set the operation control bit of NVMCON1

For PFM and Configuration Word operations, once the control bit is set the processor will stall internal operations until the operation is complete and then resume with the next instruction. DFM operations do not stall the CPU.

Since the unlock sequence must not be interrupted, global interrupts should be disabled prior to the unlock sequence and re-enabled after the unlock sequence is completed.

Figure 12-6. NVM Unlock Sequence Flowchart

NVM Unlock Sequence for PFM word write

   BCF     INTCON,GIE      ; Recommended so sequence is not interrupted
   MOVF    UpperAddr,W     ; set the target address
   MOVWF   NVMADRU
   MOVF    HighAddr,W
   MOVWF   NVMADRH
   MOVF    LowAddr,W
   MOVWF   NVMADRL   
   MOVF    HighByte,W      ; high byte of word to be written
   MOVWF   NVMDATH         ; store in high byte transfer register
   MOVF    LowByte,W       ; low byte of word to be written
   MOVWF   NVMDATL         ; store in low byte transfer register
   BSF     NVMCON0,NVMEN   ; Enable NVM operation
   MOVLW   55h             ; Load first unlock byte
; –------------------ Required Sequence –-----------------------------
   MOVWF   NVMCON2         ; Step 1: Load first byte into NVMCON2
   MOVLW   AAh             ; Step 2: Load W with second unlock byte
   MOVWF   NVMCON2         ; Step 3: Load second byte into NVMCON2
   BSF     NVMCON1,WR      ; Step 4: Set WR bit to begin write
; –-------------------------------------------------------------------
   BSF     INTCON,GIE      ; Re-enable interrupts
Important:
  1. Sequence begins when NVMCON2 is written; steps 1-4 must occur in the cycle-accurate order shown. If the timing of the steps 1 to 4 is corrupted by an interrupt or a debugger halt, the action will not take place.
  2. Opcodes shown are illustrative; any instruction that has the indicated effect may be used.