Format micro sd using ESP32

how can i format sd cad(delete all things) fat32 or ...

//SD
#include <SPI.h>
#include <SD.h>
const int SD_cs = 5;  // Pin connected to the CS line of SD card module
File file;
//SD

void setup(){
    SD.begin(SD_cs);
}

i tired this but this is not what i want. coz i have some corrupted files and some dir that exist but cant be deleted and i cant create new files in sd

void sd_format() {
    File root = SD.open("/");
    if (root) {
        File entry = root.openNextFile();
        while (entry) {
            String path = String(entry.name());
            if (entry.isDirectory()) {
                deleteFilesInSD_Dir(entry);  // Delete all files in the directory
                SD.rmdir(path.c_str());   // Remove the empty directory
            } else {
                SD.remove(path.c_str());  // Remove the file
            }
            entry = root.openNextFile();  // Move to the next file or directory
        }
    }

}


void deleteFilesInSD_Dir(File dir) {  // Delete all files inside a directory
    File entry = dir.openNextFile();
    while (entry) {
        String path = String(entry.name());
        if (!entry.isDirectory()) {
            SD.remove(path.c_str());  // Remove the file
        }
        entry.close();  // Close the entry after deleting
        entry = dir.openNextFile();  // Move to the next file
    }
}

if i go in PC and do quick format then sd card is fixed. but problem is how can i make with esp32

I just spent 1 min but this looks like it will work

Yes, SdFat has an example sketch called SdFormatter.ino. It will completely erase the card before formatting it, which is something your PC can't do.

Why can't my PC do a complete format? Which PC, Mac, Win or Linux?

Well it depends on what you mean by a complete format. The SD Association provides a formatting tool. It will do a quick format just fine. But if you ask it to wipe the card, it will write zeros to every sector, which can take hours. Similarly, I believe your computer operating system only communicates with an SD reader, which is usually a USB device even if it's internal. And I don't think there are any commands in the driver for erasing the card. At least I've never seen any indication that my PC can do that. Macs and Linux machines may be able to do that.

The Arduino, in contrast, communicates directly with the card's controller, and can issue commands to erase the entire card in only a few seconds. This is not the same as writing zeros or FFs. The flash is actually erased.

Another device that can do this is your fancy camera that offers the option of a "low level" format. Cameras need this so they can save 4K video to the SD card at high speed, which benefits from having the flash pre-erased so the new data can be saved without erasing first.

If you research this on Google, you'll get a wide variety of BS responses claiming that formatting will erase the card, or "wipe" the card. Part of the problem is terminology, in that "erase" means different things to different experts. But technically it means returning the flash memory to its original unprogrammed state. That's not at all the same as "overwrite".

Maybe we can persuade @fat16lib to rule on this question. He's the author of SdFat.

i opened SD card in pc and i see :

only .txt files i was abble to create . other folder and files were random created.

Sorry, I wasn't thinking of just SD cards but of the Format command in Windows that offers the Quick and the full format. On the Mac, I can even specify passes (I just checked, and it says at the highest security, some data recovery can still happen)
I do have one of those 'fancy cameras that has both SD and CF cards. I am aware that many photographers have lost images due to card wear even using the cards with 3 digit price tags.
Thank you for the education, and my apologies for my 'off the cuff' answer that was off the mark.

Why can't my PC do a complete format? Which PC, Mac, Win or Linux?

Most adapters for SD cards and PC apps don't have access to the SD low level hardware erase commands.

SdFat uses these commands to erase entire regions of flash with just a few bytes transferred to the SD.

Here is the loop in the SdFormatter example that erases card flash in 134,217,728 byte chunks.

I timed erase for a 128 GB Samsung Evo using a Uno R3. Here is the output with each dot representing a chunk. Total time was 4.362 seconds.

Card size: 128.18 GB (GB = 1E9 bytes)
Card size: 119.37 GiB (GiB = 2^30 bytes)
Card will be formated exFAT

Erasing
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
................................................................
...........................................................
Time: 4362 ms
All data set to 0x00
Erase done

So the UnoR3 erased the card at 29.4 GB/sec.

I print the low level erase value since some flash is low level erased to 0xFF.

Thanks very much, Bill. And I assume there is no need for "multiple passes" to fully erase the card.

I have a Nano dedicated to erasing microSD cards with your SdFat. It's clearly far superior to anything I can do in Windows, including the SD formatter app from the SD Association.

Now if you can just do an eraser for thumb drives. :slight_smile:

#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(50))) {
    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.");
}

i use this code and i get

Initialization failed. Is the SD card inserted? 

tired with other working sd cards too. . when i use default sd library it can open the sd card

SD_SCK_MHZ(25)
fixed

That is my understanding. I believe the the flash chips in the SD are "Sanitized".

Block erase is how modern SSDs are Securely erased.

See this URL:

The beauty of doing this operation in a solid state drive is the sheer speed of it. We do not need to erase in a serial, bit-by-bit manner like an HDD. We can execute the BLOCK ERASE on many, many blocks simultaneously, which allows us to “sanitize” a 1TB drive in a minute or so. Other SSD capacities will scale up or down from there.

And, oh by the way, you get to re-use your drive! No more grinders or incinerators. No more folding, spindling or mutilating. Re-deploy your device, or even donate it to a local grade school without worrying about a costly data breach!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.