Hrm, getting something odd here
#include <SD.h>
File dataFile;
int done = 0;
char c;
char buffer[4];
byte index;
void setup() {
Serial.begin(9600);
Serial.println("Initializing SD card...");
pinMode(10, OUTPUT);
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
}
void loop() {
dataFile = SD.open("data.txt", FILE_READ);
if (!done) {
if (dataFile) {
index = 0;
buffer[index] = '\0';
while (dataFile.available()) {
c = dataFile.read();
if (c == '\n' || c == '\r') {
parseBuffer();
index = 0;
buffer[index] = '\0';
} else if (index < 39) {
buffer[index++] = c;
buffer[index] = '\0';
}
}
done = 1;
dataFile.close();
Serial.println();
Serial.println("Done reading file.");
} else {
Serial.println("error opening data.txt");
}
}
}
void parseBuffer() {
if (strlen(buffer) > 0) {
int vals[] = {0, 0, 0, 0, 0};
byte index = 0;
char *token = strtok(buffer, ",");
while (token) {
vals[index] = atoi(token);
token = strtok(NULL, ",");
}
// print vals
for (int i = 0; i < 5; i++) {
Serial.print(vals[i]);
Serial.print(" - ");
}
Serial.println();
}
}
Data file contains:
90,2,90,2,5
45,4,135,4,2
135,4,45,4,2
90,2,90,2,5
The ouputs the following to the serial monitor:
Initializing SD card...
initialization done.
5 - 0 - 0 - 0 - 0 -
5 - 0 - 0 - 0 - 0 -
5 - 0 - 0 - 0 - 0 -
5 - 0 - 0 - 0 - 0 -Done reading file.
On a side note, why can't I use 'i < sizeof(vals)' ? When I try that, I get a different output:
Initializing SD card...
initialization done.
5 - 0 - 0 - 0 - 0 - 2268 - 0 - 1297 - -1534 - 397 -
5 - 0 - 0 - 0 - 0 - 2268 - 0 - 1297 - -1534 - 397 -
5 - 0 - 0 - 0 - 0 - 2268 - 0 - 1297 - -1534 - 397 -
5 - 0 - 0 - 0 - 0 - 2268 - 0 - 1297 - -1534 - 397 -Done reading file.