Writing and reading EEPROM

Made a test program to make sure I’m reading and writing to EEPROM correctly, and maintaining my data structure.

At the moment, I write and then read in setup.

I’m expecting to see in my serial monitor:
ss written loaded 124, but what I actually get is sswsswri�

I’m writing 245 to signify that I should increment the first dimension of the array, and looking for 255 (blank) to check for completion of loading.

Not quite sure what I’m doing wrong. I feel like I’m committing some kind of error by reading and writing in setup after each other. Perhaps it’s running a while loop out of setup() ?

Help appreciated.

//Array of bytes storing patches in banks

#include <EEPROM.h>

byte patches[20][53] = {0};

bool loaded = false;


void setup() {
    Serial.begin(9600);
      Serial.print("ss");
//
patches[14][45] = 124;
writeMemory();
      Serial.print("written");

  loadMemory();
    Serial.print("loaded");

  Serial.print(patches[14][45]);
}

void loop() {

}


void writeMemory() {
  byte data;
  int address = 0;
  int prevP = 0;
  for (int p = 0; p < 20; p++) {
    for (int v = 0; v < 50; v++) {
      if (prevP != p) {
        data = 245;
      } else {
        data = patches[p][v];
      }
      EEPROM.update(address, data);
      address++;
    }
  }
}

void loadMemory() {
  int value;
  int p = 0;
  int v = 0;
  int i = 0;
  while (loaded == false) {
    value = EEPROM.read(i);
    if (value == 255) {
      loaded = true;
    }
    else if (value == 245) {
      p++;
      i++;
      v = 0;
    }
    else if (value < 244) {
      patches[p - 1][v] = value;
      i++;
      v++;
    }
  }
}

EDIT: I’m using a Mega. 20*53 equates to about 2kb, so I should be fine for memory, even with other data.

Which Arduino? You may be running out of RAM. 20x53 is an awfully big data structure for an Arduino.

Your first value written is a 0

Which means your first value read is 0.

In the loadMemory function ‘p’ is 0, and you access it like this (due to the value read being 0): patches[p - 1][v] = value;

When you write to memory that is actually parts of the CPU or RAM that is already taken, you’ll most likely see resets which ends up showing things like sswsswri

Nice one, thanks. That's got it. I changed the initialisation of prevP to -1 to accound for the first reading of if (prevP != p)

It seems like all the values in the second dimension of the array have been pushed back by one position though... fairly likely given all the +1s all over the place.

Moved the v++ iterator to before the loading itself. Not an amazing solution but it does the job.

v++;
patches[p - 1][v] = value;
i++;