Accessing EEPROM  
Almost all of the controllers in MegaAVR Family has internal EEPROM, which is as we know a kind of Non-Volatile Memory. We can use this memory to store variable those we dont want to lose in no power conditions.

It allows single byte read or write at a time, but by writing efficient code we can store and retrieve 16bit variable like unsigned int to/from EEPROM.

WinAVR Gcc compiler provides very rich labrary support for accessing 8bit and 16 bit variable to/from EEPROM.

MegaAVR series controller has three different register to handle all operations related to internal EEPROM.

1. EEAR EEPROM Address Register

2. EEDR EEPROM Data Register

3. EECR EEPROM Control Register



EEDR EEPROM Data Register

This is an 8-bit register. Data from a location in EEPROM cannot be transferred to location in RAM directly when reading from EEPROM. Similarly, data to be written to EEPROM must be first placed in this register.


EEAR- EEPROM Address Register

Address of location in EEPROM from/to which data is to be read/written has to be first transferred to this register. ATmega16 has 512 bytes of EEPROM. So this register has two bytes- EEARH (High byte) and EEARL (low byte).


EECR- EEPROM Control Register

This register controls operation of EEPROM. It has 8 bits- each having its special meaning. A programmer must use this register to control operations.





/******************************************************************
Example program to read and to write in EEPROM sector of AVR.
This program stores and retrives the variable from/to EEPROM and shows previous stored value on LCD connected to PORTB as explained in LCD tutorial.
Burn this program and power off the system you will find that each you power on your system variable value do not reset while it maintain its value.
******************************************************************/

#include<avr/io.h>
#include<util/delay.h>
#include<compat/deprecated.h>
#include<avr/eeprom.h>
#include<lcd.h>

unsigned int ech EEMEM=0;

void itoa(uint16_t num)
{
unsigned char a,b,c,d,e;
a=num%10;
num=num/10;
b=num%10;

num=num/10;
c=num%10;
num=num/10;
d=num%10;
num=num/10;
e=num%10;
lcd_data(0x30+e);
lcd_data(0x30+d);
lcd_data(0x30+c);
lcd_data(0x30+b);
lcd_data(0x30+a);
}



int main(void)
{
DDRB=0xFF; //SET DATA DIRECTION REGISTER
PORTB=0x00;
lcd_init();
lcd_cmd(0x01);
while(1)
{
lcd_cmd(0x01);
unsigned int rch=eeprom_read_word(&ech);
itoa(rch);
rch=rch+100;
eeprom_write_word(&ech,rch);
_delay_ms(100);
}
return 0;

}

devesh@electroons.com
Best viewed at Firefox 1024x768 resolution