EEPROM read and write string

Updated on 31 August 2021
dev board WeMos D1 Mini
chip ESP8266
features EEPROM read write
This tutorial is more than 1 year old. If the steps below do not work, then please check the latest versions and the documentations of the individual tools used.

Before starting

Dependancies

Ensure the following dependancies are downloaded and available:

Buy the components

Code

Download code eeprom-esp8266.ino
#include <EEPROM.h>

// Change the STORED_WORD is another string
String STORED_WORD = "cactus_2";
String answer = "";

void setup() {
  EEPROM.begin(512);
  Serial.begin(115200);

  Serial.println("Store word " + STORED_WORD + " in EEPROM");
  writeWord(STORED_WORD);
}

void loop() {
  Serial.print("Read word from EEPROM: ");
  answer = readWord();
  Serial.println(answer);

  Serial.print("Word length: ");
  Serial.println(answer.length());

  delay(2000);
}

void writeWord(String word) {
  delay(10);

  for (int i = 0; i < word.length(); ++i) {
    Serial.println(word[i]);
    EEPROM.write(i, word[i]);
  }

  EEPROM.write(word.length(), '\0');
  EEPROM.commit();
}

String readWord() {
  String word;
  char readChar;
  int i = 0;

  while (readChar != '\0') {
    readChar = char(EEPROM.read(i));
    delay(10);
    i++;

    if (readChar != '\0') {
      word += readChar;
    }
  }

  return word;
}

Makefile

.PHONY: lint compile upload clean

lint:
	cpplint --extensions=ino --filter=-legal/copyright,-readability/casting *.ino

compile:
	arduino-cli compile --fqbn esp8266com:esp8266:d1_mini ./

upload:
	arduino-cli upload -p /dev/cu.wchusbserial1410 --fqbn esp8266com:esp8266:d1_mini ./

clean:
	rm -f .*.bin
	rm -f .*.elf

flash: lint compile upload clean

Serial console

Serial output from the firmware.

EEPROM read and write string serial console

Description

Write a string to ESP8266’s EEPROM and read it back without knowing its word length by locating the null character \0.

References