Hi,
I'm trying to read an array from the configuration file stored on SDcard but without luck, I get strange looking output rather than numbers stored in a file. My file structure has only 3 entries, it's a one column, three rows:
4000
200
3000
My initial idea was to create an array and the read it selectively, eg. when I need to read number in 2nd row only.
This is the code that I done so far:
int set[2],i=0;
void setup(void){
if (SD.begin(SS)){
DBG_OUTPUT_PORT.println("SD Card initialized.");
hasSD = true;
}
File conf = SD.open("conf.ini");
if (conf)
{
while (conf.available())
{
for(i=0;i<2;i++)
{
set[i]=conf.parseInt();
}
conf.close();
}
} else {
Serial.println("Cannot open file!");
}
for(i=0;i<2;i++)
{
Serial.print(set[2]);
}
Output:
107481972010748197
What I'm doing wrong?
How are you writing to the file?
Does each row have carriage return / line feed?
.
The "set" array has only two elements, set[0] and set[1]. Here you are printing the nonexistent set[2] element:
Serial.print(set[2]);
Also, you're closing the file before you're done reading it. Move "conf.close()" to outside the "while (conf.available())" loop.
These are the codes that are writing your data into the SD Card and reading them back correctly.
#include<SPI.h> //sD card uses SPI Bus
#include<SD.h> //contains library functions
#define CSPIN 4 //selecting DPin-4 does not require to set direction
//if using any pin, the direction must be made output (pinMode(DPin, OUTPUT);)
File myFile; //file pointer variavle declaration
void setup()
{
Serial.begin(9600);
SD.begin(CSPIN); //SD Card is initialized
SD.remove("Test1.txt"); //remove any existing file with this name
myFile = SD.open("Test1.txt", FILE_WRITE); //file created and opened for writing
if(myFile) //file has really been opened
{
myFile.println(4000);
myFile.println(200);
myFile.println(3000);
myFile.close();
}
myFile = SD.open("Test1.txt", FILE_READ); //file created and opened for writing
if(myFile) //file has really been opened
{
while(myFile.available())
{
Serial.print((char)myFile.read()); //prints : 4000 2003 3000 in column form
}
myFile.close();
}
}
void loop()
{
}
Hi guys, sorry for late reply, but I was't able to find my post
Thanks for any advise.
I cannot understand the way how C and C++ work, I grew up on Python which is easier and more intuitive for me.
GolamMostafa:
These are the codes that are writing your data into the SD Card and reading them back correctly.
...
Great it works! Now let say file contains not only numbers but also strings and mixed names like: qwerty1234.
How to read them correctly in this scenario.