This is a sample code which I use in working with the PIC18 microcontroller. This is tested with the PIC18F45K22, but could easily be adapted to any other PIC after updating the registers needed for the EEPROM. Refer to the specific PIC datasheet you are working with for any updates.
//This is the function which will write data to the EEPROM in the specified location
void EEPROM_putc(unsigned char address, unsigned char data) { static unsigned char GIE_Status; // Variable to save Global Interrupt Enable bit
EEADR = address; EEDATA = data;
EECON1bits.EEPGD= 0; // 0 = Access data EEPROM memory EECON1bits.CFGS = 0; // 0 = Access Flash program or DATA EEPROM memory EECON1bits.WREN = 1; // enable writes to internal EEPROM
// Disable interrupts, Next two lines SHOULD run without interrupts GIE_Status = INTCONbits.GIE; // Save the Global Interrupt Enable bit INTCONbits.GIE = 0; // Disable global interrupts
EECON2=0x55; // Required sequence for write to internal EEPROM EECON2=0xaa; // Required sequence for write to internal EEPROM
EECON1bits.WR = 1; // Required sequence to start the write cycle INTCONbits.GIE = GIE_Status; // Restore the Global Interrupt Enable bit EECON1bits.WREN = 0; // Disable EEPROM writes
while (EECON1bits.WR); // Wait for the write cycle to complete
if(EECON1bits.WRERR) { //printf("ERROR: writing to EEPROM failed!n"); }
PIR2bits.EEIF=0; //Clear EEPROM write complete flag. (must be cleared in software. So we do it here) }
//This is the function which is used to read from the EEPROM. It takes the address of the character which you wish to read, and will return the value of the character.
unsigned char EEPROM_getc(unsigned char address)
{
EEADR=address;
EECON1bits.EEPGD= 0; // 0 = Access data EEPROM memory EECON1bits.CFGS = 0; // 0 = Access Flash program or DATA EEPROM memory