3

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.

Ravi Sharma
  • 63
  • 2
  • 12

2 Answers2

2

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); 

}
tabish
  • 274
  • 3
  • 10
0

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278