I connected the SD card to Arduino as it's explained here. The problem is that the Arduino writes only once to the SD card and I don't understand the reason.
#include <SD.h>
#include <SPI.h>
int CS_PIN = 4;
File file;
void setup() {
Serial.begin(9600);
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);
Serial.print("Initializing SD card...");
if (!SD.begin(CS_PIN)) {
Serial.println("Card failed, or not present");
return;
}
Serial.println("card initialized.");
}
void loop() {
String dataString = "TEST";
File dataFile = SD.open("datalog.txt");
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
Serial.println(dataString);
} else {
Serial.println("error opening datalog.txt");
}
delay(1000);
}
The output on Serial Monitor:
Arduino write only one time on SD card error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt error opening datalog.txt
I also tried to use:
SD.open("file.txt", O_RDWR | O_APPEND);
SD.open("file.txt", O_RDWR | O_CREAT);
As I saw Adding data to an SD card file, but it doesn't work.
3 Answers 3
You are opening the file in read mode but should be opening it in write mode. Change File dataFile = SD.open("datalog.txt");
to File dataFile = SD.open("datalog.txt", FILE_WRITE);
.
You can remove this line of code: digitalWrite(10, HIGH);
.
The arduino.cc website is also an excellent source of information regarding the SD library.
File dataFile = SD.open("datalog.txt");
Repeatedly opening the same file is probably not a good practice, if you want to retain previously written contents.
For people having the same problem. I had the same problem where the SD Card would only run the if statement once and then not read it anymore. For some reason, after I ran the CardInfo, DumpFile, and ReadWrite example scripts in the SD Library (changing the title of the SD.open() command to the one that I was using), my code began to work and it started running the if statement each time. I would recommend trying this if you're experiencing the same problem.
-
Interestingly enough, I was having a problem opening a file on my SD Card using the SD Card Reader Sensor and my Elegoo Mega2560 and running the CardInfo example ( on the SD Library) solved it for me. The first time the CardInfo example gave an error, and then (just saying what I did) I popped my SD Card and put it back in and then ran the CardInfo example again and then it worked. So... If you guys are having any problems. Try using the CardInfo example from the SD Library and re-insert your SD Card.David– David2022年03月13日 21:37:14 +00:00Commented Mar 13, 2022 at 21:37
-
this indicates problems with the CS pin2022年03月14日 05:18:36 +00:00Commented Mar 14, 2022 at 5:18
setup
. then write data inloop
. after all data has been written, close the file