I tried the code below to format an SD card using the SDFat library on an ESP32, and it works fine. However, when I try to read the SD card using the default Arduino SD.h library, it fails. Specifically, SD.begin(SD_cs) does not work, and the card cannot be read.
Interestingly, I can still open the SD card on my PC without any issues. and add files there
Has anyone encountered a similar problem or know how to fix this?
#include <SPI.h>
#include <SdFat.h>
const uint8_t chipSelect = 5; // Define the chip select pin for the SD card module
SdFat SD; // Create an SdFat object
void setup() {
Serial.begin(115200);
while (!Serial) {
; // Wait for serial port to connect (needed for native USB)
}
Serial.println("Type 'format' to format the SD card.");
}
void loop() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
command.trim();
if (command == "format") {
formatSDCard();
}
}
}
void formatSDCard() {
// Initialize the SD card with default SPI pins
if (!SD.begin(chipSelect, SD_SCK_MHZ(25))) {
Serial.println("Initialization failed. Is the SD card inserted?");
return; // Exit the function if initialization fails
}
// Attempt to format the SD card
if (!SD.format()) {
Serial.println("Formatting failed.");
return; // Exit the function if formatting fails
}
Serial.println("Formatting completed successfully.");
}
