MCU Examples.com
PIC Microcontroller Project Examples, free source codes and resources collection.
Writing and reading to internal EEPROM is pretty easy and following example demonstrates this functionality. Its write and read functions are reusable and should work on any PIC18F family microcontroller.
MPLAB project source available at end of the page.
// // Designed by www.MCUExamples.com // rasika0612@gmail.com // Enternal EEPROM read and write example // #include <p18f4520.h> #pragma config OSC = HS // 20MHz Crystal, (HS oscillator) #pragma config PBADEN = OFF // PORTB<4:0> pins are configured as digital I/O on Reset) #pragma config WDT = OFF // watch dog timer off #pragma config LVP = OFF // Low voltage program off void int_EEPROM_putc(unsigned char address, unsigned char data); unsigned char int_EEPROM_getc(unsigned char address); void main() { unsigned char c; int_EEPROM_putc(0x12,0x34); //Write 0x34 to EEPROM address 0x12 Nop(); c = int_EEPROM_getc(0x12); // Read EEPROM address 0x12 in to variable C while (1) { } } //This function Writes data to given address in internal EEPROM of PIC MCU void int_EEPROM_putc(unsigned char address, unsigned char data) { unsigned char INTCON_SAVE; 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 INTCON_SAVE=INTCON; // Save INTCON register contants INTCON=0; // Disable interrupts, Next two lines SHOULD run without interrupts EECON2=0x55; // Required sequence for write to internal EEPROM EECON2=0xaa; // Required sequence for write to internal EEPROM EECON1bits.WR=1; // begin write to internal EEPROM INTCON=INTCON_SAVE; //Now we can safely enable interrupts if previously used Nop(); while (PIR2bits.EEIF==0)//Wait till write operation complete { Nop(); } EECON1bits.WREN=0; // Disable writes to EEPROM on write complete (EEIF flag on set PIR2 ) PIR2bits.EEIF=0; //Clear EEPROM write complete flag. (must be cleared in software. So we do it here) } // This function reads data from address given in internal EEPROM of PIC unsigned char int_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 EECON1bits.RD = 1; // EEPROM Read return EEDATA; // return data }
You can download MPLAB project files here