OK - so It's unlikely that I'll travel over 999,999 miles, and although it matters to optimise, at the moment I'm just after a proof of coding.
#include <SD.h>
const int SD_CS_PIN = 9; // SD
File dataFile;
char distance;
char *token;
char delim[] = " ";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
SD.begin(SD_CS_PIN);
dataFile = SD.open("odometer.txt");
if (dataFile) {
while (dataFile.available()) {
token = strtok(dataFile, delim);
}
}
}
void loop() {
// put your main code here, to run repeatedly:
}
But this errors:
sketch_nov03a.ino: In function 'void setup()':
sketch_nov03a:19: error: cannot convert 'SDLib::File' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'
token = strtok(dataFile, delim);
^
exit status 1
cannot convert 'SDLib::File' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'
But I thought SDLib::File was a char... can't find out what it should be.
if (dataFile) {
while (dataFile.available()) {
x = dataFile.read();
if ( x >= 48 && x <= 57 ) {
Serial.print("x: ");
Serial.println(x);
y = x - 48;
Serial.print("y: ");
Serial.println(y);
}
}
}
In C, strings are arrays of char that are terminated with a an ascii NUL '\0'.
Read one character at a time.
Put the characters into an array of char[] that will be big enough to hold all the characters plus one.
When you get to the end of the line or the end of the file, add a terminating '\0' to the string.
This creates a C string that the various string.h functions will work with, eg "9999.7\0".
For extra credit:
Do not use a floating point number for any number that needs to be precise. For an odo reading, read in the characters, skip the decimal point, and if necessary pad out the number to a fixed number of decimal places. Convert that number into a long rather than a float.
So if the file contains 123.45, put "12345\0" into your string. If it contains "123.1", put "12310" into your string. I suggest you name variables that hold these "whole number of hundredths of a mile" with a suffix that indicates the unit, say "cMi" for centi-miles. In metric, of course, pad it out to three decimal places and use metres.
n1md4:
At least now I know what beast I'm dealing with. I now need an elegant way to concatenate them together.
Like this. No need for strings:
long total = 0;
if (dataFile) {
while (dataFile.available()) {
x = dataFile.read();
if ( x >= '0' && x <= '9' ) {
Serial.print("x: ");
Serial.println(x);
y = x - '0';
Serial.print("y: ");
Serial.println(y);
total = total * 10 + y;
Serial.print("total: ");
Serial.println(total);
}
}
}
Your code reads the characters one at a time rather than collecting them together and then converting them into a long. This example uses the Serial object, but is similar to reading data from an SD card.