1

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.

  • don't you need a mode when opening? – dandavis Aug 13 '17 at 11:17
  • open the file in setup. then write data in loop. after all data has been written, close the file – jsotola Nov 30 '17 at 8:02
1

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.