eeprom_read_byte() reading the LAST stored value, HELP me...

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Using ATmega8 with internal crystal 1MHZ and WINAVR to write code..

This is my code sample which is writing decimal 6 at EEPROM location 0 and decimal 1 at EEPROM location 10.
Reading back value from EEPROM location 0 returns be 1 decimal which is incorrect. This code always reads back the last value stored by eeprom_write_byte functions?
Can any one help me in this...?

#include 
#include 
#include 
int main(void)
{
	//uint8_t addr;	
	//static uint8_t v;
	uint8_t addr;	
	uint8_t v;
		addr=0;
		eeprom_write_byte(&addr,6) ; //0.45Amp
		_delay_ms(1);
		addr=10;
		eeprom_write_byte(&addr,1) ; //0.45Amp
		_delay_ms(1);
		addr=0;
	DDRB=0xff;
	v=eeprom_read_byte(&addr);
	v=eeprom_read_byte(&addr);
	PORTB=v;
return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Change like this:

eeprom_write_byte(&addr,6) ;
eeprom_write_byte( (void *)addr, 6) ;

v=eeprom_read_byte(&addr);
v=eeprom_read_byte( (void *)addr);
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I think you need to typecast to the type of integer being written/read, and in the case of the write_byte macro it needs to be typecast to a constant. Specifically:

eeprom_write_byte(&addr,6) ;
eeprom_write_byte( (static uint8_t *)addr, 6) ;

v=eeprom_read_byte(&addr);
v=eeprom_read_byte( (uint8_t *)addr);

To the OP: The reason your code was failing was because you were writing to the address of the "addr" variable, rather than at the location pointed to by addr. Since the address of addr lies in SRAM the EEPROM pointer registers are being filled with garbage.

You can also declare your EEPROM variables outside your functions to give them symbolic names. See my tutorial located here.

- Dean :twisted:

Make Atmel Studio better with my free extensions. Open source and feedback welcome!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks TroyLee... Its working.... Do visit http://www.deccancode.com Your suggestions on my website are welcome.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks Dean,
Your explanation is really an eye opener.


To the OP: The reason your code was failing was because you were writing to the address of the "addr" variable, rather than at the location pointed to by addr. Since the address of addr lies in SRAM the EEPROM pointer registers are being filled with garbage.