How to stop variables resetting when arduino is off

I want my variables to maintain the new value they got from void loop() and not reset when arduino is turned off then back on.
Here is an example I have been trying on:

int x;

void setup(){

Serial.begin(9600);

}

void loop() {

Serial.println(x);

x++;

delay(2000);

}

Read about eeprom
You might need a bit of extra hardware to save to eeprom only upon power off (or use non volatile FRAM Adafruit I2C Non-Volatile FRAM Breakout - 256Kbit / 32KByte : ID 1895 : $9.95 : Adafruit Industries, Unique & fun DIY electronics and kits)

1 Like

When a variable changes state you can write it to EEPROM then at power up, read what was previously saved.

If the variable changes often, detect when there is an inevitable power fail then write things to EEPROM before all power is gone.

1 Like

There is a limit on writes the EEPROM can do, ~ 100,000 erase write cycles.

1 Like

Welcome to the forum

Consider the use of an SD card and write the values to be saved to it each time they are changed then read them back in setup() when the board is powered up

2 Likes
E E P R O M
l r r e n m
e a o a l e
c s g d y m
t a r o
r b a r
i l m y
c e m
a a
l b
l l
y e

You can use this library, works for ESP and Arduino I think ESP32 Save Data Permanently using Preferences Library | Random Nerd Tutorials

It works for me on an ESP8266

Flash memory used to simulate eeprom on ESP is even worse than real eeprom with only 10,000 write… don’t kill your ESP…

Does this apply the same way to uploading code?
= does this mean after uploading code for 10.000 times (not that easy to reach a number of 10.000 times uploading code ) but out of scientific curiosity:

After 10.000 times uploading code the flash-memory starts to become unreliable?

yes - your ESP life's is limited.

assuming you upload code 50 times a day for testing, you have 200 days ahead of you to complete the project :slight_smile:

after 10,000 you are out of specs so weird stuff can happen

I read elsewhere that Espressif is using modules spec-ed for 100,000 writes though... so your mileage may vary

there is also Wear Levelling going on

on commercial projects I use FRAM
after control parameters are updated they are saved to FRAM
on powerup or reset parameters are restored from FRAM

Then I too recommend using FRAM.
FRAM has a lot of write-cycles 10^14 = 100.000.000.000.000 writecycles

that's why I suggested that in post #2 :wink:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.