SD.Begin does not initiate!

void SaveGPIOsToSDcard(int RelayNumber, int GPIOoldState, int GPIOnewState){
  SD.begin(5);
  if(SD.exists("/Relay_GPIOs_States/states.txt")){
    File StatesFile = SD.open("/Relay_GPIOs_States/states.txt", FILE_READ);
    if(StatesFile){
      String oldstr, updstr, StatesFileStr;
      oldstr = "relay"+(String)RelayNumber+"="+(String)GPIOoldState;
      updstr = "relay"+(String)RelayNumber+"="+(String)GPIOnewState;
      StatesFileStr = GetStatesFileString();

      //Open the states file in write mode and update the contents
      SD.begin(5);
      if (!SD.remove("/Relay_GPIOs_States/states.txt")){Serial.println("The old states file could not be deleted! GPIO states update failed!");
      } else{
          File StatesFile = SD.open("/Relay_GPIOs_States/states.txt", FILE_WRITE);
          if (StatesFile){
          StatesFileStr.replace(oldstr, updstr);
          StatesFile.print(StatesFileStr);
          StatesFile.close();} else{Serial.println("The old states file deleted but the updated one could not be created! GPIO states update failed!");}}
    } else{Serial.println("The states file could not be opened for update initiation! GPIO states update failed!");}
  } else{Serial.println("The states file could not be opened for update. Check SD card, directory or file availability! GPIO states update failed!");}
}
void setup() {

//SD card module CS pin
pinMode(5, OUTPUT);

  Serial.begin(115200);
}

The above is my code. When I try SaveGPIOsToSDcard (1, 1, 0);, it does NOT do anything. The file and path surly exist.
Any suggestions please?

It looks like a hen's breakfast because you didn't use code tags. Please fix.

1 Like

SD.begin() returns a boolean. I would check that before moving on.

Check out this example: SD card example – Arduino Learning

1 Like

Read the forum guidelines to see how to properly post code and some hints on how to get the most from this forum.
Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

1 Like

I fried the hen!
Delicious for breakfast!

The third line does not return true while I think it should!

If by "the third line does not return true" you mean this one:

if(SD.exists("/Relay_GPIOs_States/states.txt")){

then there is a really excellent chance that the file does not exist or is in some other directory.

1 Like

I'm not sure but I thought one created the object before setup and the begin in the setup code.

1 Like

it is a good idea to put serial print every step of the way while you are debugging so that you can clearly see which part of the program run and which doesn’t.

1 Like

Unfortunately, the path is correct and the file in the directory exist.
Checked several times...

Serial shows that the line if(SD.exists("/Relay_GPIOs_States/states.txt")) does not return true while file is there!
Has "SD.begin" or "file.read" a timeout?
Should I explicitly call "SD.end()" after each use of "SD.open()"?

Start at the beginning.

Try the simple ReadWrite SD example in the IDE, it does work.

If that example does not work, you have a problem with your SD or how its wired.

1 Like

This is the code I created (from other examples) to test out my SD card:

/*
  SD card read/write
  Mod 01 make file name a string and iterate until we find a unused file name.
  Mod 02 add capability to increment filename.
  Rev 03 tested successfully on Arduino M0

  SD card attached to SPI bus on ICSP Header.
  SD Board power = 5V (for large board with EEPROM)

  based on code created: Nov 2010 by David A. Mellis, 9 Apr 2012 by Tom Igoe
  This code is in the public domain.

driver has a 512 byte buffer then write to SD

Closing the file forces any buffered data to be written to the SD and also updates
the file's directory entry.

If you don't close the file, you will lose all data written the file since it was opened,
not just the last buffer, since the directory entry will not be updated.
*/

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

// *** SD Card declarations **************************************************
// ***************************************************************************

#define SDCARD_CS_PIN 4

uint8_t fileNumb = 100;
char dataFile[8];
bool SD_Error = false;

File myFile;			// create instance of a "File" class

void setup() {
  SerialUSB.begin(115200);
  delay (2000);
// Initializing SD card....
  if (!SD.begin(SDCARD_CS_PIN))
    {SerialUSB.print("initialization failed");
     SD_Error = true;
    }

// loop until we find a file that doesn't already exist.......
  do
    {
     itoa(fileNumb, dataFile, 10);  // (value, Array, base)
     const char *extension = ".csv";
     strcat(dataFile, extension);  // syntax  strcat(dest, source)
     ++fileNumb;
    } while (SD.exists(dataFile));


SerialUSB.print("READY TO OPEN FILE FOR WRITING   = ");
SerialUSB.println(dataFile);
  myFile = SD.open(dataFile, FILE_WRITE);   // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
SerialUSB.println(myFile);
  // if the file opened okay, write to it:
  if (myFile) {
    myFile.println("data from boiler");     // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    SerialUSB.println("data from boiler");
    //SerialUSB.print(" data written to file:   ");
    myFile.close();                         // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 SerialUSB.println(dataFile);
    }
  else {
    // if the file didn't open, print an error:
    SD_Error = true;
    }
  SerialUSB.print("SD_Error = ");
  SerialUSB.print(SD_Error);
}
void loop() {
  // nothing happens after setup
}


1 Like

Results: READY TO OPEN FILE FOR WRITING = 100.csv
0
SD_Error = 1
!!!
My code writes some times and fails some times.
My SD test code results:
SD card type: SDHC
SD Card Size: 30000MB
Used space: 0MB
Remaining space: 30000MB
and my SD test code:

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

void setup() {
  Serial.begin(115200);
  if(!SD.begin(4)){
          Serial.println("SD Card mount failed!");
    } else{
      uint8_t SDcardType = SD.cardType();
  
      if(SDcardType == CARD_NONE){
          Serial.println("No SD card attached!");
          return;
      }
  
      Serial.print("SD card type: ");
      if(SDcardType == CARD_MMC){
          Serial.println("MMC");
      } else if(SDcardType == CARD_SD){
          Serial.println("SDSC");
      } else if(SDcardType == CARD_SDHC){
          Serial.println("SDHC");
      } else {
          Serial.println("UNKNOWN!");
      }
  
      uint64_t SDcardSize = SD.cardSize() / (1024 * 1024);
      uint64_t SDcardUsedSize = SD.usedBytes() / (1024 * 1024);
      
      Serial.printf("SD Card Size: %lluMB\n", SDcardSize);
      Serial.printf("Used space: %lluMB\n", SDcardUsedSize);
      Serial.printf("Remaining space: %lluMB\n", SDcardSize-SDcardUsedSize);
      
      }
}
void loop() {
  // nothing happens after setup
}

The module: ESP32 (30-pin)
I can read the file in setup, but not in "void loop".

Thank you friends. All of the responses were useful and are appreciated.
There were some LOGIC errors in the "if" commands sequence.

Happy new year!
Best wishes to all!