Ravi Sharma Ravi Sharma - 9 months ago 43
C Question

Writing and Reading data to EEPROM sequentially

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

EEPROMWrite(epadr,high); //writing at address stored in epadr
epadr++; //increment address

printf("Memory Full\n");

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

Answer Source

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