SdFat icon indicating copy to clipboard operation
SdFat copied to clipboard

SdCard has to be initialized again in loop

Open tickietackie opened this issue 4 years ago • 1 comments

I am using the SD card in the setup and loop of my program. Why do I have to initialize the SD card again there?

SdCardHandler sdCardHandler;
bool doOnce = true;

/* ------------------ Setup ------------------*/

void setup() {
#ifdef SERIAL_OUTPUT
  Serial.begin(9600);
  serialCountdown();
#endif

  sdCardHandler.initializeSdCard();
  const char* filePath = "web-build/index.html";
  DEBUG_PRINT_LN(sdCardHandler.getFileSize(filePath));  --> this works
  
}

void loop() {

  if (doOnce) {  --> this should work in some other way right?
    sdCardHandler.initializeSdCard();
    doOnce = false;
  }

  const char* filePath = "web-build/index.html";
  DEBUG_PRINT_LN(sdCardHandler.getFileSize(filePath));
  delay(10000);
}    

if I am not reinitializing the SDCard I get:

DBG_FAIL: FsCache.cpp.41
DBG_FAIL: FatFile.cpp.795
DBG_FAIL: FatFile.cpp.870
DBG_FAIL: FatFileLFN.cpp.332
DBG_FAIL: FatFile.cpp.461
SdError: 0XC,0XFF
Failed to open txt file to get file size

Extract from SdCardHandler.cpp:

#include "SdCardHandler.h"

//global sd
SdFat SD;

//static initialized 
bool SdCardHandler::initialized = false;

bool SdCardHandler::initializeSdCard() {
  // Initialize the SD.
  if (!SD.begin(CHIP_SELECT, SPI_SPEED)) {
    SD.initErrorPrint(&Serial);
    DEBUG_PRINT_LN(F("Failed to initialize SD card."));
    return false;
  } else {
    DEBUG_PRINT_LN(F("SD card successfully initialized."));
    SdCardHandler::initialized = true;
    return true;
  }
}

Pretty sure this is a scoping issue but how can I avoid this?

tickietackie avatar Jun 11 '21 20:06 tickietackie

Pretty sure this is a scoping issue but how can I avoid this?

I have no idea.

greiman avatar Jun 12 '21 12:06 greiman