-
-
Notifications
You must be signed in to change notification settings - Fork 215
Description
After removing and re-inserting an SD card, SDFS.begin() succeeds but subsequent calls to myFile.open() fail. Please see the below code...
#include <SdFat.h>
#include <SPI.h>
// --- Pin Definitions for GIGA R1 ---
#define SD_CS_PIN 10
#define ERROR_LED_IOPIN 46 // The red D7 LED on the GIGA
#define RELAY_ON LOW
#define RELAY_OFF HIGH
// --- Global Objects ---
SdFat SDFS;
// --- Helper function to control the LED ---
void ERROR_LED_SET(bool on) {
digitalWrite(ERROR_LED_IOPIN, on ? RELAY_ON : RELAY_OFF);
}
/**
-
@brief Checks for the SD card using SdFat and resets the SPI bus if needed.
*/
bool ensureSdReady() {
if (SDFS.card() && SDFS.card()->type() != 0) {
ERROR_LED_SET(false);
return true;
}Serial.println("Card not ready. Forcing full library and SPI re-initialization...");
SDFS.end();
::SPI.end();
::SPI.begin();SdSpiConfig spiConfig(SD_CS_PIN, DEDICATED_SPI, SD_SCK_MHZ(10));
if (SDFS.begin(spiConfig)) {
SDFS.chvol();
Serial.println("-> SD Card Initialization successful!");
ERROR_LED_SET(false);
return true;
}Serial.println("-> SD Card Initialization failed.");
ERROR_LED_SET(true);
return false;
}
/**
-
@brief Attempts to write one line of data to the log file.
/
void logData() {
FsFile myFile;
const char filename = "hotplug_test.txt";
char data_buf[50];if (!ensureSdReady()) {
Serial.println("Log failed: SD card not ready.");
return;
}if (!myFile.open(filename, O_WRONLY | O_CREAT | O_APPEND)) {
Serial.println("Log failed: Could not open file.");
ERROR_LED_SET(true);
return;
}sprintf(data_buf, "Logging at %lu ms\r\n", millis());
if (myFile.write(data_buf, strlen(data_buf)) <= 0) {
Serial.println("Log failed: Write error.");
ERROR_LED_SET(true);
myFile.close();
return;
}myFile.close();
ERROR_LED_SET(false);
Serial.print("Success: Wrote to ");
Serial.println(filename);
}
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println("\n--- GIGA R1 SdFat Hot-Plug Test ---");
pinMode(ERROR_LED_IOPIN, OUTPUT);
ERROR_LED_SET(false); // Start with LED off
}
void loop() {
logData();
delay(2000);
}