1

I'm working on a stage (this is my first bigger Arduino project), and I want to create an initializer for it, and for this, I want to store some variables in the memory of ESP32 WROVER-B. For this, I found this solution.

Based on their example (which works fine) I write a basic demo, using their Preferences.h:

#include <Preferences.h>

#define MAX_BUFF_LEN  255

Preferences preferences;

char c;
char str[MAX_BUFF_LEN];
uint8_t idx = 0;

void init(){
  preferences.remove("counter");
  preferences.begin("my-app", false);
  unsigned int counter = 0;
  Serial.printf("Current counter value: %u\n", counter);
  preferences.putUInt("counter", counter);
  preferences.end();
}

void readback(){
  preferences.begin("my-app", false);
  unsigned int counter = preferences.getUInt("counter", 0);
  Serial.printf("Current counter value: %u\n", counter);
  preferences.end();
}


void add(){
  preferences.begin("my-app", false);
  unsigned int counter = preferences.getUInt("counter", 0);
  counter++;
  Serial.printf("Current counter value: %u\n", counter);
  preferences.putUInt("counter", counter);
  preferences.end();
}

void setup() {
  Serial.begin(115200);
  //Serial.begin(9600);
  while (!Serial) ; // wait for serial port to connect. Needed for native USB
  Serial.println("start");
}

void loop() {
  if(Serial.available()>0){
    c = Serial.read();
    if(c != '\n')
      str[idx++] = c;
    else{
      str[idx] =  '\0';
      idx = 0;

      Serial.print("Recieved: ");
      Serial.println(str);
      if(*str == 'r')
        readback();
      if(*str == 'w')
        init();
      if(*str == 'a')
        add();
    }
  }
}

But every time I reset (I mean plug out and in) my ESP it starts counting at the beginning. Also if I disconnect the client on the serial port the same happens. What have I missed here, or how can I do it correctly?

2
  • 1
    You could try using the randomnerdtutorials.com/esp32-flash-memory EEPROM for example Commented Mar 14, 2022 at 2:50
  • @Avon97 which says "This tutorial is outdated. Follow the new tutorial instead: ESP32 Save Data Permanently using Preferences Library" Commented Mar 16, 2022 at 22:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.