cmicrocontrollermicrochipmplabpic18

How do you write and read to memory with PIC18?


I want to store a number to PIC18 then retain it even if the power is lost or the unit is reset. I think my writing code portion looks fine, just the reading portion of it looks strange after the unit is reset.

I am using the following code which I got from Microchip.

Code:

unsigned int value;
unsigned int DEEdata = 1;
unsigned int  DEEaddr = 0x04;

DataEEInit();
dataEEFlags.val = 0;

DataEEWrite(DEEdata,DEEaddr);
value = DataEERead(DEEaddr);
Nop();
printf("%d",value);

The ouput: 1

However when I reset the unit and only use the reading code I always get 255.

Code to read:

DataEEInit();
value = DataEERead(DEEaddr);
printf("%d",value);

The output: 255

Why is this happening? I am assuming maybe the value is not being saved or the reading portion is incorrect. Thank you!


Solution

  • Some PIC18 micros have an internal EEPROM in addition to the internal flash. The 18F87J11 does not have this so you have 2 options:

    1) Write to the flash memory - this is where your program is stored. make sure the number of write/read cycles is ok for your application.

    2) Use an external i2c or spi memory for your configuration settings

    The DataEEWrite you are using are from an 'eeprom emulation' library from microchip (linked in the comments below. There are a couple of things to be careful of: