SD.open in loop()

Hey
I want to open a file in the loop(), but it wont work. i don't know why.

#include <SD.h>
#include <SPI.h>



void setup() {
  Serial.begin(9600);


  // SD CARD
  // Initialize SD Card
  pinMode(5, OUTPUT);
  if (!SD.begin(5)) {
    Serial.println("Initialization of SD card failed");
  }
  else {
    Serial.println("Initialization done.");
  }
}
void loop() {
  SD.begin(5);
  File dataFile = SD.open("datalog.txt", FILE_WRITE);



  if (dataFile) {
    Serial.println("top");
  }
  else {
    Serial.println("error opening datalog.txt");
  }
  dataFile.close();
  delay(2000);
}

It should print out "top" but I just get the error massage. can any body help me?

Does the file exist?
Is it in the root directory?
What partition type in on the card?
Did you give the card enough time to initialize with the Arduino?
Have you checked out the SD examples included with the IDE?

@er_name_not_found Can I get some action on my feeling that we'd go 5 for 5 "no" or "IDK" on those questions?

a7

Even money at best. Reminds me of my first post asking about using 4 serial connections. I hadn't done the reading either.

@nnnnnnnnnnniiii In the IDE you will find many examples of how to use different components with your Arduino. Some of them are for using SD cards.
The card needs to be formatted FAT16 or FAT32. Check it all out and come back with your new code if it still doesn't work.

The one thing that jumps out at me is that you should not have the SD.begin() inside loop. You only need to initialise the SD system once. You already do this in setup(), so remove the call to begin from inside loop.

It is a bad idea to open the file, write one record, and close it again, as that vastly increases the time spent reading and writing from the card, dramatically increases the error rate, and the current draw.

Open the file once before collecting data and close it when you are done. Issue a SD.flush() command once in a while to keep the file pointers up to date.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.