hello !
My question is really simple. I'd like to know if it's possible to read a file from my SD Card on my ethernet shield without using a while loop.
I'm currently using this code :
fh = SD.open(filename);
if(fh)
{
while(fh.available())
{
Serial.println(fh.readStringUntil('\n'));
}
fh.close();
}
else
{
Serial.println("Error opening the file");
}
As you can see, using this method will "block" my sketch, and I won't be able to perform any actions beside reading the file.
Is there a way to allow me to read my file and still perform actions (such as blinking a led) ?
Thanks for your help!
Yes. Change to if() to only read one character at a time. Then you will need a further if() so that you only open the file once instead of opening it on every pass through the loop. Or put the file open into setup().
MorganS:
Yes. Change to if() to only read one character at a time. Then you will need a further if() so that you only open the file once instead of opening it on every pass through the loop. Or put the file open into setup().
I need to open my file at differents times during my sketch. So i can't open it in my setup().
1- I'm writing data into the file when I'm logging a RFID Tag.
2- I'm reading file to send the content through my ethernet shield. (this is why I need to read my file and still be able to perform actions).
I already tried to use a if() and it's only reading the first line of my file.
Use a flag to determine if the file is open.
boolean sdOpen = false;
if(!sdOpen) {
// open the file
sdOpen = true;
}
if(sdOpen) {
// read/write file
}
loop(){
static boolean FileIsOpen = false;
if(FileIsOpen) {
if(fh.available()){
Serial.println(fh.readStringUntil('\n'));
} else {
fh.close();
FileIsOpen = false;
} else {
if(weNeedToSendEthernetNow()) {
fh = SD.open(filename);
FileIsOpen = true;
}
}
}
MorganS:
loop(){
static boolean FileIsOpen = false;
if(FileIsOpen) {
if(fh.available()){
Serial.println(fh.readStringUntil('\n'));
} else {
fh.close();
FileIsOpen = false;
} else {
if(weNeedToSendEthernetNow()) {
fh = SD.open(filename);
FileIsOpen = true;
}
}
}
Isn't the fh.available() going to loop only once ? So it will always return the first line of my file.
Thanks for your support guys. I really appreciate it.
No, it won't go back to the start of the file because it doesn't reopen the file if it's already open.
You haven't posted enough of your code. Is fh a local or global variable?
MorganS:
No, it won't go back to the start of the file because it doesn't reopen the file if it's already open.
You haven't posted enough of your code. Is fh a local or global variable?
It's a global ! But from what I've tested from now, everything seems to be working fine thanks to you !
Thanks a lot!