Save the values on Arduino MKR after the board has been turned off and on

#include <FlashStorage.h>

FlashStorage(my_flash_store, char);
char i;

void setup() {
  Serial.begin(57600);
  while(!Serial)
  {
    
  }


  i=my_flash_store.read();
  if(i!='1'||i!='2')
  {
    i='1';
  }
}

void loop() {
  if(i == '1'){
    i='2';
    my_flash_store.write(i);
    Serial.println("done");
  }
  Serial.println(i);
  delay(1000);
}

As shown in the code, I’d like to initialize the character i to ‘1’ during setup and change its value to ‘2’ in the main loop. My idea is to remember the latest value of i when the board has been turned off (which is ‘2’ in this case) and retrieve the value when it is on again.
However, the Flashstorage seems doesn’t work and whenever I reconnect the power to the board, i has been reset to ‘1’ as I can always see “done” in my monitor.
Does anyone know what’s going on when we cut the power of a board and then turn it on again without rewriting the program? Is there any way to store the value in the main loop and retrieve it when we repower the board?

Thanks

hansng:

  if(i!='1'||i!='2')

i can never be both '1' and '2', so this will always evaluate to true.

When you're experiencing unexpected behavior, always throw some Serial.println() in your code to see what the actual values are. A print of i before this statement would have probably been very helpful to you.

pert:
i can never be both '1' and '2', so this will always evaluate to true.

When you're experiencing unexpected behavior, always throw some Serial.println() in your code to see what the actual values are. A print of i before this statement would have probably been very helpful to you.

It works! Thank you very much.
Does it mean that all the variables will be lost after power off and the system will run setup() again once been repower?

hansng:
Does it mean that all the variables will be lost after power off

No. The flash memory you write to with the FlashStorage library is non-volatile, meaning the data is preserved even after you power off the board.

However, you should note that the flash memory is cleared every time you upload a new sketch:

hansng:
the system will run setup() again once been repower?

Yes. setup() runs every time you power on the board.

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