Saving an integer to SD card, retrieving the number and then using math operations on it

I can't help thinking that this is far more difficult than it needs to be. What I have been trying to do for days now is to save an integer to SD card, retrieve the integer later and then use mathamatical operations on it.

To be specific I want to save an integer, which will be around 1010 decimal, and later compare it (greater than, less than or equal to) with a similar value integer. I have written a sketch which uses Open Weather Maps to download a JSON object and use the data therein to display weather information. Air pressure alone doesn't tell one much, for it to be useful one needs to know if it is increasing or decreasing and and so want to save the air pressure reading so I can compare old and new readings. BUT to save battery power I shutdown my device and start it up again every half hour, so I need the SD card (or EEPROM) to save the air pressure data during shutdown and to retrieve it again after the startup in order to compare it with the new air pressure value.

Here's hoping someone can help me with what, with my limited knowledge, is proving to be a nightmare of incompatible variable types (char, Strings, strings, double, int, etc. etc.etc.). The main problem is that most explanations concentrate on printing out the result of retrieving the save onto a serial monitor, that's simple. But using the result as a variable which can be manipulated is proving most difficult.

What you want to do sounds trivial using EEPROM. Whatever data type it is, save it to an EEPROM location using EEPROM.put(location, valueToSave);

When the system wakes up, use EEPROM.get(location, valueToRead); to read it back again

Of course, the usual caveat about the EEPROM only having a limited number of write cycles for each location applies

1 Like

Thanks. Actually I think I have found a way to do it via the SD card;

File myFile;
String parameter;

void ReadSYFile(){
    myFile = SD.open("/test.txt");
  if (myFile) {
    Serial.println("/test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      //  int result = Serial.write(myFile.read());
      char c = myFile.read();
      if (isPrintable(c)) {
        parameter.concat(c);
      }
    }
    Serial.println(parameter);
    
    // Don't forget to close the file!!!
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

And then calling the function.

  ReadSYFile();
  int result = parameter.toInt() * 2;
  Serial.println(result);

This needs work but in principal it seems to work.For instance I could make the function an int and return the actual integer rather than working with a global String.

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