Accessing internal EEPROM AVR
How to access Internal EEPROM in AVR ATmega8/16/32
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 wrote 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 Data Register
Address of location in EEPROM from/to which data is to be read/written has to be first transferred to this register. ATmega32 has 1024 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.
EERE (bit 0) - If written 1, read operation on address specified in EEAR is started.
EEWE (bit 1)- If this bit is written 1 (after setting bit EEWME), write operation on address specified in EEAR is started in next cpu cycle. After write operation is completed, controller will clear this bit automatically.
EEWME (bit 2)- If this bit is written 1, prior to setting EEWE to 1, EEPROM write is started. Other wise write operation is not started.
EERIE (bit 3)- If this bit is written 1, an interrupt is generated when write operation is completed.
Code for 16 bit variables like unsigned int etc.
#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)
{
DDRD=0xF4; //SET DATA DIRECTION REGISTER
DDRC=0x30;
PORTD=0x00; //SET 1 for OUTPUT PORT
DDRB=0x00; //SET 0 FOR INPUT PORT
PORTD=0x00;
PORTB=0xFF;
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;
}
For more info about avr Library try this project site http://www.nongnu.org/avr-libc/user-manual/



