I've been having an unusual problem writing to SD cards using the sparkfun microSD shield and a 4gb card. Bascially, the arduino reports that the file opens and closes ok, but the data does not actually appear in the resulting file. The code below reproduces the error very reliably, however the exact amount of data that is written to the file varies.
This code should produce a file that contains integers that increment by 2 indefinitely, one number per line:
0
2
4
6
8
...
The reported serial output seems to behave as expected:
setup complete
delaying: 0
delay complete
file open
write complete
delaying: 2
delay complete
file open
write complete
delaying: 4
delay complete
file open
write complete
delaying: 6
delay complete
file open
write complete
delaying: 8
...
...but the file that is actually written is something like:
0
2
4
(End of File)
Setup:
- Arduino UNO R3
- Arduino Software 1.0.3 and included "SD.h" library
- Fat32-formatted 4GB (SanDisk)
- sparkfun miroSD shield
Code to reproduce:
#include <SD.h>
const int chipSelect = 10;
File dataFile;
int t_delay = 0;
void setup()
{
Serial.begin(9600);
// make sure that the default chip select pin is set to output
pinMode(10, OUTPUT);
digitalWrite(10, LOW);
// see if the card is present and can be initialized, otherwise halt
if (!SD.begin(chipSelect)) halt();
Serial.println("setup complete");
}
void loop()
{
// make a test string to write
String dataString = String(t_delay);
Serial.print("delaying: ");
Serial.println(dataString);
// wait some amount of time between writes
delay(t_delay);
Serial.println("delay complete");
// if the file is available, write to it, otherwise stop and wait
dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
Serial.println("file open");
dataFile.println(dataString);
dataFile.flush();
dataFile.close();
Serial.println("write complete");
}
else halt();
// increment counter
t_delay = t_delay + 2;
}
// this function is an infinite loop that halts the arduino
void halt()
{
while (1==1) {
Serial.println("halted");
delay(500);
}
}
Any suggestions would be greatly appreciated!
Thanks,
-Jon