Datasheet

PICkit™ 3 Debug Express Lessons
© 2009 Microchip Technology Inc. DS41370C-page 59
A read of an EEPROM byte begins by clearing the EEPGD bit in EECON1. This selects
the data EEPROM array for access. The CFGS bit should also be cleared during an
EEPROM access; it is only set to access the Configuration bit locations.
The byte address of the data EEPROM location to be read is loaded into the EEADR
register. The RD bit in EECON1 is then set to execute the read. On the next instruction
cycle, the value of the read EEPROM location is available in the EEDATA register.
Figure 3-50 shows a function that reads a byte of EEPROM.
FIGURE 3-50: DATA EEPROM READ
3.10.2 Writing a data byte to EEPROM
Similar to a read, a write to the internal EEPROM must clear the EEPGD and CFGS
bits in EECON1 to access the internal EEPROM array. The data value to be written is
then written to the EEDATA register. The address of the byte to be written is loaded into
EEADR.
Before a write can take place, the WREN bit in EECON1 must be set, or the write will
not occur. It is also necessary to write a sequence of two bytes, values 0x55 and 0xAA
to EECON2 immediately before beginning the write by setting the WR bit in EECON1.
Both the WREN bit and the EECON2 sequence are to protect against inadvertent
writes to EEPROM and ensure the integrity of EEPROM values.
The three step sequence of:
EECON2 = 0x55;
EECON2 = 0xAA;
EECON1bits.WR = 1;
must be completed in this order, without other statements or interruptions or the write
will not execute. Therefore, if interrupts are enabled, they should be disabled before the
sequence and re-enabled after the WR bit is set.
EEPROM writes take some time to erase and program the byte in the array. This time
is listed as parameter D122 in the data sheet Section 26.0 “Electrical Characteristics”,
and is usually several ms. During this time, the PIC18F45K20 microcontroller continues
to execute program code. The program may determine when a write has completed by
polling or by an interrupt generated by the EEPROM module.
In the example write function in Figure 3-49, the code waits for the EEPROM write to
complete by polling the WR bit of EECON1. When the write is complete, this bit will be
cleared. Alternatively, the program can be alerted that the write has been completed
with an interrupt. The EEPROM module will set the EEIF bit in PIR2 when the write
completes.
unsigned char EEPROM_Read(unsigned char address)
{ // reads and returns the EEPROM byte value at the address given
// given in "address".
EECON1bits.EEPGD = 0;// Set toaccessEEPROMmemory
EECON1bits.CFGS= 0;// Do notaccessConfigregisters
EEADR = address;//Load EEADRwith address of location to write.
// execute the read
EECON1bits.RD = 1;//Set the RDbit to execute the EEPROM read
//The value read is ready the next instruction cycle in EEDATA. No wait is
//needed.
return EEDATA;
}