News:

;) This forum is the property of Proton software developers

Main Menu

EEPROM write and read in new PIC18F-Q devices - example

Started by trastikata, Today at 06:09 PM

Previous topic - Next topic

trastikata

Here's an example how to write and read EEPROM in new PIC18F-Q devices.

Device = 18F57Q83   
Declare Xtal = 64 

'Load some data to be written
Dim bTemp As Byte = 0xBC
 
'Verify command and DFM base in datasheet for corresponding PIC
Symbol EEPROM_WRITE_COMMAND = %00000011
Symbol EEPROM_READ_COMMAND =  %00000000
Symbol DFM_BASE = 0x38

Main:
    If EepromWrite(0,bTemp) = 0 Then    'If successfully written in EEPROM address 0
        bTemp = EepromRead(0)           'Read back EEPROM address 0
    EndIf
   
    End

'wAddress = EEPROM address to be written
'Result: 0 - write success
'        1 - write error
Proc EepromWrite(wAddress As Word, bData As Byte), Byte
    Dim bTempGIE As Byte

    Result = 0
    'Clear previous error flags
    NVMCON1.7 = 0
   
    'Address (DFM base + offset)
    NVMADRU = DFM_BASE
    NVMADRH = wAddress.Byte1
    NVMADRL = wAddress.Byte0
    'Data
    NVMDATL = bData
    'Select command
    NVMCON1 = EEPROM_WRITE_COMMAND
    'Disable GIE
    bTempGIE = INTCON0
    INTCON0.7 = 0
    'Unlock sequence
    NVMLOCK = 0x55
    NVMLOCK = 0xAA
    'Start
    NVMCON0.0 = 1
    'Wait to complete
    While NVMCON0.0 = 1 : Wend
    'Check for an error   
    If NVMCON1.7 = 1 Then      
        NVMCON1.7 = 0 
        Result = 1             
    EndIf
    'Restore GIE
    INTCON0 = bTempGIE  
    'Disable write
    NVMCON1 = 0
EndProc

'wAddress = EEPROM address to be read from
'Result: Data
Proc EepromRead(wAddress As Word), Byte
    Result = 0
    'Address (DFM base + offset)
    NVMADRU = DFM_BASE
    NVMADRH = wAddress.Byte1
    NVMADRL = wAddress.Byte0
    'Select command
    NVMCON1 = EEPROM_READ_COMMAND
    'Start
    NVMCON0.0 = 1
    'Wait to complete
    While NVMCON0.0 = 1 : Wend
    'Copy result
    Result = NVMDATL
EndProc