Preference not working when pressing button in esp32

I am working on a counter project using esp32 in which I want to store the value of counter in esp32 using preferences library when a button is pressed. It works when the code is

#include <Arduino.h>
#include<Preferences.h>

Preferences preferences;

int val = 0;
void setup(){
         Serial.begin(115200);
         preferences.begin("counter", false);
         val = preferences.getUInt("val",0);
         val++;
         Serial.println(val);
         preferences.putUInt("val",val);
}
void loop(){
}

It doesn't work when the code is

#include <Arduino.h>
#include<Preferences.h>

Preferences preferences;
#define reset 26

void save();

int val = 0,flag = 0;
void setup(){
       Serial.begin(115200);
       pinMode(reset, INPUT_PULLUP);
       preferences.begin("counter", false);
       val = preferences.getUInt("val",0);
       val++;
       Serial.println(val);
}
void loop(){
        if(digitalRead(reset) == 0){
        save();
       }
}
void save(){
        if(flag==0){
           preferences.putUInt("val", val);
           flag++;
        }
}

I am using platformio and android framework

This only runs once. Is that what you want it to do?

1 Like

like was mentioned when does flag get set back to 0?

I have edited the code to store the value when the button is being pressed, and I want to do it only once for testing purposes. but it is not storing

Okay.

The next thing I would check is whether save is called at all. You could add a Serial.println message to check this.

Yes, I added a Serial.println and it is printing , so save is being called. That's why Im so confused

Hmm. What happens when you additionally use preferences.end()?

Nothing happens actually. I am so confused why it is not storing the value when it put inside switch beign pressed

val is incremented in setup()

Hey @ZX80 , yeah you're right. So when the code the runs it should store val + 1 right? but it is not storing and getUInt gives the old value. But If use the 1st code that I posted ,every time when I reset esp32 val is getting incremented and storing

does not make it the reset pin.
So your sketch goes through setup() only once.
No matter how many times you press your button on pin 26.

I meant reseting esp32 using the en button on the esp32

If the objective is to increment val in setup and to save the new value using the button on pin 26,
it works with

void save(){
        if(flag==0){
           preferences.putUInt("val", val);
           preferences.end();
           flag++;
        }

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