Sign in Join
Wiki copytemporary

AVR Embedded Tutorial - EEPROM

Deutsch · English

Read and write EEPROM data

This code in this tutorial is for an Atmega328/Arduino with 16MHz. For how to control the UART with UARTInit and UARTSendString(..., see the UART Tutorial.

Accessing the EEPROM

Every single byte in the EEPROM can be accessed via an address. This gives you the opportunity to read and write each character individually.

Writing data

Note: The two lines with EECR must be separate, otherwise nothing is written!

pascal
procedure EEPROM_write(Address : int16; Data : byte);
  begin
    // Check if ready to write
    while (EECR and (1 shl EEPE)) <> 0 do 
      begin
        ;
      end;

    EEAR := Address;
    EEDR := Data;                   // Byte to write
    EECR := EECR or (1 shl EEMPE);  // There must be 2 lines!
    EECR := EECR or (1 shl EEPE);
  end;

Reading data

pascal
function EEPROM_read(Address : int16) : byte;
  begin
    // Check if ready to read
    while (EECR and (1 shl EEPE )) <> 0 do 
      begin
        ;
      end;

    EEAR   := Address;
    EECR   := EECR or (1 shl EERE);
    Result := EEDR;                  // Read byte
  end;

Example

Sample code that shows how to read and write data.

pascal
 const
   sc = 'Hello World!';

 var
   i : integer;
   s : shortString; 

 begin
   UARTInit ;

   // Write string, including length byte
   for i := 0 to Length (sc) do 
     begin
       EEPROM_write(i, byte(sc[i]));
     end;

   // Read string, including length byte
   SetLength(s, EEPROM_read(0));         // Read length byte

   for i := 1 to Length(s) do 
     begin
       s[i] := char(EEPROM_read(i));     // Read string data bytes
     end;

   repeat
     UARTSendString(s);
     UARTSendString(#13#10);
   until 1 = 2;
 end.

Once the first routine (above) has been executed, you can easily see with the second routine (below) that "Hello World!" was stored in the EEPROM, even if you have disconnected the ATmega from the power in the meantime.

pascal
 var
   i : integer;
   s : shortString;

 begin
   UARTInit;

   // Read string, including length byte
   SetLength(s, EEPROM_read(0));          // Read length byte

   for i := 1 to Length(s) do 
     begin
       s[i] := char(EEPROM_read(i));
     end;

   repeat
     UARTSendString(s);
     UARTSendString(#13#10);
   until 1 = 2;
 end.

See also


From the Free Pascal wiki, page "AVR Embedded Tutorial - EEPROM", as it stood on 2020-01-26 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.