SD.Begin does not initiate!

void SaveGPIOsToSDcard(int RelayNumber, int GPIOoldState, int GPIOnewState){
    File StatesFile ="/Relay_GPIOs_States/states.txt", FILE_READ);
      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
      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 ="/Relay_GPIOs_States/states.txt", FILE_WRITE);
          if (StatesFile){
          StatesFileStr.replace(oldstr, updstr);
          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);


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:


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 "" a timeout?
Should I explicitly call "SD.end()" after each use of ""?

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() {
  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.......
     itoa(fileNumb, dataFile, 10);  // (value, Array, base)
     const char *extension = ".csv";
     strcat(dataFile, extension);  // syntax  strcat(dest, source)
    } while (SD.exists(dataFile));

  myFile =, FILE_WRITE);   // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  // 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();                         // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  else {
    // if the file didn't open, print an error:
    SD_Error = true;
  SerialUSB.print("SD_Error = ");
void loop() {
  // nothing happens after setup

1 Like

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.println("SD Card mount failed!");
    } else{
      uint8_t SDcardType = SD.cardType();
      if(SDcardType == CARD_NONE){
          Serial.println("No SD card attached!");
      Serial.print("SD card type: ");
      if(SDcardType == CARD_MMC){
      } else if(SDcardType == CARD_SD){
      } else if(SDcardType == CARD_SDHC){
      } else {
      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!