Loading and updating variables from SD card

Hi,

I am trying to write a program that will write the current values of parameters in a program to an SD card, then load them after a reboot. I can create the file on the SD card but I can't work out how to read and update the parameters. I need different versions of the variables, shown with the ID field, and then can select e.g. ID 1 and load the 3 values in the row. Example file is below.

ID, Length, Width, Height
1, 10, -64, 4.8
2, 16, 5.2, 18
3, 26, -1, 68

| ID |Length|Width|Height|
| 1 | 10 | -64 | 4.8 |
| 2 | 16 | 52 | 18 |
| 3 | 26 | -1 | 68 |

I have tried using parseInt & parseFloat, however that only works for a single line, not being able to select the line I need. It also seems to be quite slow to read the data. If anyone has an idea for a method I would love to hear it!

while (myFile.available()) {

            ID = myFile.parseInt();
            Length = myFile.parseInt();
            Width = myFile.parseInt();
            Height = myFile.parseFloat();

Hello

It would be easier if your lines were all the same length, each field having a constant width (easy with sprintf)

For example, each field is max 4 characters, and a space between fields

  10  -64  4.8
 123  152   18

So that you can use file.seek, because you know a line is always (e.g.) 15 characters, so the start of a line is always a multiple of 15 (for example, line 2 is at position 15 in the file). Then you read 14 characters ( 15 minus the \n ) from the start of a line, and you can then use sscanf or strtok to parse the line

Thanks guix!

Could you help me with some example code?

Here is an example (without line parsing, but it's easy) : t1049536.ino - Wokwi Arduino and ESP32 Simulator

Another advantage of using lines/fields of same length, is that you can update one field in the file without needing to rewrite the whole file.. Simply seek to the desired line and field (think as X, Y coordinates), and write the new value of the field :slight_smile:

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