Search code examples
cavreeprom

AVR Eeprom Understanding


I have started to create a button counter and was successful in doing that then I shifted myself to reading and writing eeprom I tried to use the eeprom to read and write a single byte and was also successful in doing so, pretty basic stuff. Recently I tried to use the eeprom_update_word function which is a little confusing to me as I think doesn't work quite well I had tried but was successful can someone help me? Below is what I have written:

 // removed the standard header as they aren't displayed here!

void lcd_num (int);


int main(void)
{
    uint16_t c = 0;
    DDRD = 0x00;

    lcd_init(LCD_DISP_ON);
    lcd_string(5, 0, "COUNTER");
    lcd_command(0xC5);
    // check if value has already been used/initialized...
    if (eeprom_read_word((uint16_t*)10) == UINT16_MAX)
    {
        // ...if not, init to 0
        eeprom_write_word((uint16_t*)10 , 0);
    }
    else
    {
        // ...if yes, read value back
        c = eeprom_read_word((uint16_t*)10);
    }
    lcd_data(c+48);

    while(1)
    {
        if( (PIND & 0x01) == 1 )
        {
            c++;
            lcd_command(0xC5);
            lcd_num(c);
            eeprom_update_word((uint16_t*)10, c);
            while( (PIND & 0x01) == 1 );
        }
        if((PIND & 0x02) == 1)
        {
            eeprom_write_word((uint16_t*)10,0);
            c = eeprom_read_word((uint16_t*)10);
            while((PIND & 0x02) == 1);
        }
    }
}



void lcd_num(int n){
    lcd_data((n/1000)+48);
    n %= 1000;

    lcd_data((n/100)+48);
    n %= 100;

    lcd_data((n/10)+48);
    n %= 10;

    lcd_data(n+48);
}
            void lcd_num(int n){
            lcd_data((n/1000)+48);
            n %= 1000;

            lcd_data((n/100)+48);
            n %= 100;

            lcd_data((n/10)+48);
            n %= 10;

            lcd_data(n+48);
        }

Can I ask for another favour here? I want to use a manual button to erase the eeprom so that I may not run out of space I have tried this but this doesn't work. Am i doing this correct ??


Solution

  • Currently, your counter value gets overwritten on each restart. You need to do some kind of check, whether the EEPROM location was already initialized (default EEPROM content is all 0xFF).

    // check if value has already been used/initialized...
    if (eeprom_read_word((uint16_t*)10) == UINT16_MAX)
    {
        // ...if not, init to 0
        eeprom_write_word((uint16_t*)10 , 0);
    } 
    else 
    {
        // ...if yes, read value back
        c = eeprom_read_word((uint16_t*)10);
    }