0

I am having a bit of trouble loading values stored on an SD card and assigning them to variables within my program. I can achieve this as one big block of data, but would much prefer them to be saved to variables whilst in a loop or some other process.

My txt file has the following 6 ints & floats values, which are displayed vertically in the file:

2 0.003200 312 1 0.720000 8

Each of these values I want assigned to variables data1,....2,3,4,5,6. Unfortunately, the code I use below will never achieve this, but I am clueless as to any theory to solve this problem. Thanks in advance.

myFile = SD.open("test.txt", FILE_READ);
    if (myFile) {
    while (myFile.available()) {
        data = myFile.read();
    }
myFile.close();
}
else {
    Serial.println("Read Error");
}
  • These are values that change if anyone's thinking why don't I just hard code it instead. – user4163554 May 5 '18 at 20:22
  • Putting all such variables in a struct could be a good choice, as you can then copy the contents of the struct as raw data to/from the card (though getting at it from another system like a PC would require knowledge of how the Arduino compiler packs structs). But you can also read the variables one by one; the big problem at present is that your code doesn't have any variables that it even attempts to load from the card. – Chris Stratton May 6 '18 at 21:22
1

File implements Stream just like Serial. so you can use parseInt and parseFloat

int n = File.parseInt();
float x = File.parseFloat();
Serial.println(n);
Serial.println(x, 6);
| improve this answer | |
  • Thanks for the response. I have just had a search for readByteUntil, it sounds like it could be what I'm looking for, but how would this be implemented into my code. How would I distinguish which goes where? – user4163554 May 5 '18 at 21:10
  • Would I list the parseInts and floats according to the order within my list? And would I put this within the 'available()' method? Thanks. – user4163554 May 5 '18 at 21:11
  • in your case you do not need readBytesUntil. only parse the numbers like in the code snippet in my answer. parseInt and parseFloat skips the spaces. – Juraj May 6 '18 at 5:17
  • myFile = SD.open("test.txt", FILE_READ); if (myFile) { while (myFile.available()) { km = myFile.parseInt(); kmTemp = myFile.parseFloat(); kmrevs = myFile.parseInt(); miles = myFile.parseInt(); milesTemp = myFile.parseFloat(); milesrevs = myFile.parseInt(); Serial.println(km); ........other printlns() } myFile.close(); } else { Serial.println("Read Error"); } – user4163554 May 6 '18 at 9:10
  • Is that what you mean. I could only squeeze in so many characters in this comment. – user4163554 May 6 '18 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.