EEPROM Emulation with Arduino API

Updated on 3 September 2021
dev board RobotDyn M0 Mini
firmware Arduino
features eeprom flash
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:

Pre-requisites

Try these simpler or similar examples:

Buy the components

Code

Download code eeprom-emulation-samd21.ino
#include <FlashAsEEPROM.h>

void setup() {
  SerialUSB.begin(115200);
  delay(100);
}

void loop() {
  if (!EEPROM.isValid()) {
    SerialUSB.println("EEPROM is empty, writing some example data:");

    storeInFlash();
    SerialUSB.print("");
  } else {
    SerialUSB.println("EEPROM has been written.");
    SerialUSB.print("Total length of EEPROM is ");
    SerialUSB.println(EEPROM.length());
    SerialUSB.println("Here is the content of the first 20 bytes:");
    SerialUSB.print("->");

    readFromFlash();
    SerialUSB.println("");
  }

  delay(5000);
}

void storeInFlash() {
  for (int i = 0; i < 20; i++) {
    EEPROM.write(i, 100+i);
    SerialUSB.print(" ");
    SerialUSB.print(100+i);
  }

  EEPROM.commit();
}

void readFromFlash() {
  for (int i = 0; i < 20; i++) {
    SerialUSB.print(" ");
    SerialUSB.print(EEPROM.read(i));
  }

  SerialUSB.println();
}

Makefile

BOARD?=arduino:samd:mzero_bl
PORT := $(shell ls /dev/cu.usbmodem*)

.PHONY: default lint all flash clean

default: lint all flash clean

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

all:
	arduino-cli compile --fqbn $(BOARD) ./

flash:
	arduino-cli upload -p $(PORT) --fqbn $(BOARD) ./

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

Serial console

Serial output from the firmware.

EEPROM Emulation with Arduino API serial console

Description

Read and write to the flash memory of a SAMD21 board (E.g. Arduino M0 or RobotDyn SAMD21 M0-Mini) with the EEPROM Arduino API.

The following APIs are used in the example:

  1. EEPROM.isValid()
  2. EEPROM.length()
  3. EEPROM.commit()
  4. EEPROM.write
  5. EEPROM.read

References

Watch