EEPROM read and write numbers

Updated on 31 August 2021
dev board Arduino UNO
firmware Arduino
chip ATmega328P
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.

Buy the components

Code

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

int values[] = {23, 254, 255, 256, 257, -1, -2};
int addr = 0;
int arraySize = sizeof(values) / sizeof(values[0]);

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

  Serial.println("");
  Serial.println("");

  // EEPROM size is 1024 bytes on the ATmega328P
  Serial.print("Arduino EEPROM length: ");
  Serial.println(EEPROM.length());

  // Each EEPROM element is 1 byte
  Serial.print("Array length to write and read: ");
  Serial.println(arraySize);

  for (int index = 0; index < arraySize; index++) {
    EEPROM.write(addr, values[index]);
    delay(10);

    Serial.print("Writing ");
    Serial.print(values[index]);
    Serial.print(" in address ");
    Serial.println(addr);

    addr++;
  }

  EEPROM.write(addr, "\0");
  EEPROM.read(addr);

  Serial.println("");
  Serial.println("Begin reading back the array: ");
  int currentAddr = 0;
  int readInt;

  while (currentAddr < arraySize) {
    Serial.print("Reading ");
    readInt = EEPROM.read(currentAddr);

    Serial.print(readInt);
    Serial.print(" in address ");
    Serial.println(currentAddr);

    currentAddr++;
  }
}

void loop() {}

Makefile

BOARD?=arduino:avr:uno
PORT?=/dev/cu.usbmodem14*

.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 .*.hex
	rm -f .*.elf

Serial console

Serial output from the firmware.

EEPROM read and write numbers serial console

Description

Read and write a series of numbers in the EEPROM and in the process learn about the fact that each EEPROM element is 1 byte. Discover, how overflow numbers beyond 255 and negative numbers get stored.

References