PIC18F Writing to eeprom fails 2nd time

Status
Not open for further replies.

alifred

Member
I am using a PIC18F4550, and have implemented the following code to read/write to/from eeprom, following the asm example in the datasheet, and other examples found on this site.

The code works fine for the first write, but the verify fails on the 2nd write. (returns -2).

I assume that it is because I am not clearing a flag somewhere but am not entirely sure about this.

Code:
unsigned char readee(unsigned short address)
{
	if(address > 1024 || address < 0)
		return 0;

	EECON1 = 0;
	EEADR = (unsigned char)address;
	EECON1bits.RD = 1;
	
	return EEDATA; //Data should now be on the EEDATA register. (Only takes 1 clock)
}
unsigned char rdata;
char writeee(unsigned short address, const unsigned char data)
{
	if(address > 1024 || address < 0)
		return -1;
	
	//Configuration
	EECON1 = 0;
	EECON1bits.WREN= 1;

	EEADR = (unsigned char)address;
	EEDATA = data;
	
	DIS_INT(); //Disable interupts while writing
	
	EECON2 = 0x55;
	EECON2 = 0xAA;

	EECON1bits.WR = 1;
	
	EN_INT(); //Enabled them again now

	while(!PIR2bits.EEIF); //wait until finished
	
	EECON1bits.WREN = 0;
	
	//Now lets perform a verify
	rdata = 0;
	rdata = readee(address);
	if(data != rdata)
	{
		//Data was not written correctly.
		return -2;
	}
	
	//Data written and verified correctly
	return 0;
}

Thanks in advance.
Ali
 
I have sorted this out myself, I was not clearing the EEIF bit, which is set by the hardware, when the eeprom is written correctly.

Software is required to reset the bit.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…