(SOLVED)ESP32 Preferences Read/Write Weird Problem

Thread Starter

iimagine

Joined Dec 20, 2010
501
Been so long since i started dabbling in coding...
The problem: The code below can read and write to preferences file fine, but only show the correct wrote value for the anglePID when an update command is received ("U"). The other, which is velocityPID, only show all 0s; only when a command "R" (Reset) is received, will it properly display the correct wrote value....
Both pids are from the same class PID, which have the same method for reading and writing. What weird is that why does anglePID get loaded properly but velocityPID? It would only load correctly when I do a "R" command for reload.
This is killing me!
C-like:
void onWebSocketMessage(char *data) {
  if (*(data + 1) == '.') {
    PID *pid = NULL;
    switch (*data) {
      case 'A': pid = &anglePID; break;
      case 'V': pid = &velocityPID; break;
    }
    if (pid) {
      switch (*(data + 2)) {
        case 'P': pid->P = atof(data + 3); break;
        case 'I': pid->I = atof(data + 3); break;
        case 'D': pid->D = atof(data + 3); break;
        case 'S': pid->S = atof(data + 3) * DEG_TO_RAD; break;
        case 'W': {
            preferences.begin("Settings", false);
            pid->saveSettings(preferences);
            preferences.end();
            break;
          }
        case 'R': {
            preferences.begin("Settings", false);
            pid->loadSettings(preferences);
            preferences.end();
            webSocket.textAll(pid->getSettings());
            break;
          }
      }
    }
  } else if (*data == 'U') {
    preferences.begin("Settings", false);
    anglePID.loadSettings(preferences);
    velocityPID.loadSettings(preferences);
    preferences.end();    
    webSocket.textAll(anglePID.getSettings() + ";" +
                      velocityPID.getSettings());
  }
}
 
Last edited:

Thread Starter

iimagine

Joined Dec 20, 2010
501
OMG!!!
Took me a whole day to try and figure this out. First i thought it was some multithreading problem, then i thought it was a pointer problem....ect... Turns out that i have to begin and end preferences loading for each pid like this: (Annoyingly STUPID)
C-like:
    preferences.begin("Settings", false);
    anglePID.loadSettings(preferences);
    preferences.end();   
    preferences.begin("Settings", false);
    velocityPID.loadSettings(preferences);
    preferences.end();
 
Top