Hi, I'm trying to read a .csv file from a sd card. The format of the file is ID | Location | Color | Availability. It should be int | string | string | string. When using my code it reads the wrong values from the file. It also returns some squares for one of the strings.
#include <CSV_Parser.h>
#include <SPI.h>
#include <SD.h>
const int chipSelect = 10;
int test = 0;
void setup() {
Serial.begin(9600);
delay(3000);
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1);
}
Serial.println("card initialized.");
CSV_Parser cp(/*format*/ "dsss", /*has_header*/ true, /*delimiter*/ ';');
cp.parseLeftover();
if (cp.readSDfile("/Land.csv")) {
int16_t *ID = (int16_t*)cp["ID"];
char **Lokasjon = (char**)cp["Lokasjon"];
char **Farge = (char**)cp["Farge"];
char **Utvalg = (char**)cp["Utvalg"];
Serial.print(ID[1],DEC); Serial.print(" - ");
Serial.print(Lokasjon[1]); Serial.print(" - ");
Serial.print(Farge[1]); Serial.print(" - ");
Serial.print(Utvalg[1]);
}
}
The output: 12 - Alaska - Lilla - �
NB : (The lastone is four squares!)
It should return: 2 - Alaska - Lilla - Rosa
When plugged in to my pc and prited as HEX? Because I dont know how to do that.
The output from the IDE when using cp.print();:
5 | Albania | Rosa | AV
2 | Alaska | Lilla | Rosa
6 | Brazil | Bla | Lilla
1 | Danmark | Hvit | Bla
4 | Norge | Rod | Hvit
3 | Sverige | Gronn | Rod
7 | USA | Gul | Gronn
9 | Australia | Konge Bla | Gul
8 | Spania | Oransje | Konge Bla
10 | Portugal | AV | Oransje
Which arduino board are you using? The actual parsing and print statements are working, using a local char array instead of an SD card, but the code seems a bit memory intensive, so you may be short of ram.
I suspect you need more ram. I modified your sketch to run from fixed data, and get correct output, but this will not run on an atmega328, uses too much memory (and I do not use the 512 bytes of ram used by the SD buffer):
Accessing values by column name:
2 - Alaska - Lilla - Rosa
CSV_Parser content:
rows_count = 10, cols_count = 4
Header:
ID | Lokasjon | Farge | Utvalg
Types:
int16_t | char* | char* | char*
Values:
5 | Albania | Rosa | AV
2 | Alaska | Lilla | Rosa
6 | Brazil | Bla | Lilla
1 | Danmark | Hvit | Bla
4 | Norge | Rod | Hvit
3 | Sverige | Gronn | Rod
7 | USA | Gul | Gronn
9 | Australia | Konge Bla | Gul
8 | Spania | Oransje | Konge Bla
10 | Portugal | AV | Oransje
Memory occupied by values themselves = 165
sizeof(CSV_Parser) = 44
This my be more efficient on memory and storage? This is just a sample file, the finished project would contain 370 rows. So I am actually looking for a method to just read on line from csv, do some stuff with it in the arduino, and the the next line and so on. Could this be better for that method?
strtok() works in place, so it requires no new storage. It modifies the original input string in order to break it into C-string tokens (by replacing the delimiter characters with zero bytes).