Arduino EEPROM read/write string

May 11, 2019

arduino | cpp | eeprom
#include <EEPROM.h>

write null terminated string at “address”

void writeString(int address, String data)
{
  int stringSize = data.length();
  for(int i=0;i<_size;i++)
  {
    EEPROM.write(address+i, data[i]);
  }
  EEPROM.write(address + stringSize,'\0');   //Add termination null character
}

read string from “address”

String readString(int address)
{
  char data[100]; //Max 100 Bytes
  int len=0;
  unsigned char k;
  k = EEPROM.read(address);
  while(k != '\0' && len < 100)   //Read until null character
  {
    k = EEPROM.read(address + len);
    data[len] = k;
    len++;
  }
  data[len]='\0';
  return String(data);
}

gist code block


comments powered by Disqus