I need to access large amount of data in my project. Did some researching and came across this site explaining that it is better and faster to store it in .dat file then in .csv:
So I made sketch that populates array of structs with values read from .csv file on SD card and then writes those structs in .dat file on SD card for later use:
#include <SD.h>
const int chipSelect = 53;
File csvFile;
File dataFile;
struct skyObject {
char type[10];
char name[20];
char constelation[12];
};
struct skyObject stars[10];
void setup() {
Serial.begin(9600);
pinMode(chipSelect, OUTPUT);
SD.begin(chipSelect);
if (!card.init(SPI_HALF_SPEED, chipSelect)) {
Serial.println("initialization failed");
return;
} else {
Serial.println("wiring is correct and a card is present");
}
/*
* reading .csv file from SD card
* and populatingstruct with read values
*/
csvFile = SD.open("stars.txt", FILE_READ);
if(csvFile){
Serial.println("file opened");
int i = 0;
int j = 0;
char csvField[20];
int fieldNo = 1;
char temp;
while(csvFile.available()){
temp = csvFile.read();
csvField[j] = temp;
j++;
if(temp == ',' || temp == '\n'){
csvField[j - 1] = '\0';
switch(fieldNo){
case 1:
strcpy(stars[i].type, csvField);
break;
case 2:
strcpy(stars[i].name, csvField);
break;
case 3:
strcpy(stars[i].constelation, csvField);
break;
}
fieldNo++;
csvField[0] = '\0';
j = 0;
}
if(temp == '\n'){
i++;
fieldNo = 1;
}
}
csvFile.close();
}else{
Serial.println("error opening file");
}
//checking if struct is populated --- it is
for(int i = 0; i < 10; i++){
Serial.print(stars[i].type);
Serial.print('\t');
Serial.print(stars[i].name);
Serial.print('\t');
Serial.println(stars[i].constelation);
}
/*
* Writing array of structs in .dat file on SD card
*/
dataFile = SD.open("stars.dat", FILE_WRITE);
if(dataFile){
for(int i = 0; i < 10; i++){
dataFile.write((const uint8_t *)&stars[i], sizeof(stars[i]));
delay(50);
}
dataFile.close();
}
}
void loop() {
// put your main code here, to run repeatedly:
}
It stores values from .csv to struct... they are printed in Serial monitor.
But it doesn't write them in .dat file. File remains empty (0 bytes).
And I have tried storing handwriten struct like this:
skyObject stars[4] = {
{"Sirius", "45.67876", "17.5432"},
{"Rigel", "56.45675", "38.9273"},
{"Castor", "11.00236", "56.37109"},
{"Pica", "126.30078", "30.09989"}
};
and it works fine.
Can someone please point me in the right direction...