3
votes

I am working on my college project which needs to store data in EEPROM of AtMega32. I am able to write and read data at any particular location of memory. But when I try to write data sequentially form address 0 to 1023 I am getting wrong values.

Here are the functions I have written.

Function definition to read and write data

#include "eeprom.h"

uint8_t EEPROMRead(uint16_t uiAddress)
{
    /* Wait for completion of previous write */
    while(EECR & (1<<EEWE));
    /* Set up address register */
    EEAR = uiAddress;
    /* Start eeprom read by writing EERE */
    EECR |= (1<<EERE);
    /* Return data from data register */
    return EEDR;
}

void EEPROMWrite(uint16_t uiAddress, uint8_t ucData)
{
    /* Wait for completion of previous write */
    while(EECR & (1<<EEWE));
    /* Set up address and data registers */
    EEAR = uiAddress;
    EEDR = ucData;
    /* Write logical one to EEMWE */
    EECR |= (1<<EEMWE);
    /* Start eeprom write by setting EEWE */
    EECR |= (1<<EEWE);
}

Here is main function

static int epadr=0;
epread=EEPROMRead(epadr);      //reading from address stored in epadr
printf("%d",epread);           //printing values


if(epadr<=1023)
    {
        EEPROMWrite(epadr,high);    //writing at address stored in epadr
        epadr++;                   //increment address
    }
}

if(epadr>1023)
printf("Memory Full\n");

I want to store data from location 0 to 1023. Please tell what is wrong with this code.

2
What is the definition of the EEAR, EECR, and EEDR etc variables?Dai
Where do you initialize epadr? Do you rely on zero init of static storage duration variables? Doing so is bad practice, particularly in embedded systems, that often have non-standard start-up code which skips zero initialization.Lundin
@Dai 'EEAR, EECR, EEDR' are registered defined to acsess EEPROM of AVR.Ravi Sharma
@Lundin I have initialized epadr like this "static int epadr=0;"Ravi Sharma
Btw you are aware that if(epadr<=1023) only writes to address 0 and not from 0 to 1023, yeah? There's no loop.Lundin

2 Answers

2
votes

No need to define your own function for reading and writing data in internal EEPROM. AVR provide library for this purpose. Here is the sample code:-

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/eeprom.h>

int main(void)
{
    char read[5];

    eeprom_write_byte (0, '0');
    eeprom_write_byte (1, '1');
    eeprom_write_byte (2, '2');
    eeprom_write_byte (3, '3');
    eeprom_write_byte (4, '4');

    for (int count=0;count<5;count++)
    {
        read[count]=eeprom_read_byte((const uint8_t *)(count));
    }

    while (1); 

}
0
votes

You don't wait for the read to complete before reading EEDR. There's no guarantee the value will be ready to read when you read it. You need to add about a 1ms delay after setting EERE and before reading EEDR.

See the entry under EEPROM Read/Write Procedure for more information.