Search code examples
avreeprom

EEPROM in AVR doesn't work


I'm a beginner in C language. I'm trying to operate on EEPROM memory in my ATmega 8 and ATtiny2313. Based on this tutorial I've created the following codes:

1) writes a number to place 5 in uC's eeprom

#define F_CPU 1000000UL
#include <avr/eeprom.h>


int main()
{
    number=5;

    eeprom_update_byte (( uint8_t *) 5, number );

    while (1);
    {
    }
}

2) blinks the LED n times, where n is the number read from place 5 in eeprom

#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/eeprom.h>


int main()
{
    DDRB=0xFF;
    _delay_ms(1000);

    int number;

    number=eeprom_read_byte (( uint8_t *) 5) ;

    for (int i=0; i<number; i++) //blinking  'number' times
    {
        PORTB |= (1<<PB3);
        _delay_ms(100);
        PORTB &= (0<<PB3);
        _delay_ms(400);
    }

    while (1);
    {
    }
}

The second program blinks the led many times, and it's never the amount which is supposed to be in eeprom. What's the problem? This happens in both atmega8 and attiny2313.

EDIT: Console results after compilation of the first program:

18:01:55 **** Incremental Build of configuration Release for project eeprom **** make all Invoking: Print Size avr-size --format=avr --mcu=attiny2313 eeprom.elf

AVR Memory Usage

Device: attiny2313

Program: 102 bytes (5.0% Full) (.text + .data + .bootloader)

Data: 0 bytes (0.0% Full) (.data + .bss + .noinit)

Finished building: sizedummy

18:01:56 Build Finished (took 189ms)


Solution

  • That is one of the every time failures for beginners :-)

    If you compile simply with avr-gcc <source> -o <out> you will get the wrong results here, because you need optimization! The write procedure MUST be optimized to fulfil the correct write access! So please use '-Os' or '-O3' for compiling with avr-gcc!

    If you have no idea if your problem comes from read or write the eeprom, read your eeprom data with avarice/avrdude or similar tools.

    The next pitfall can be, that you erase your eeprom section if you program your flash. So please have a look what your programmer really do! A full chip erase erases the eeprom as well.

    Next pitfall: What fuses you have set? You are running with the expected clock rate? Maybe you have programmed internal clock and your outside crystal seems to be working with wrong speed?

    Another one: Just have a look for the fuses again! JTAG pins switched off? Maybe you see only JTAG flickering :-)

    Please add the compiler and programming commands to your question!