Go Down

Topic: SD Card - Read available space? (Read 3 times) previous topic - next topic

DerekErb

I have the WiFi Shield with a 2 GB micro SD card in it. I am very pleased with writing to and reading from the SD card.

However I would like to be able to read how much space is available on the SD card before writing to it or to display / send that information elsewhere.

I went through the library functions and couldn't find anything that does this.

How can I read the amount of available space on the SD card?

Thanks!

johnwasser

You can use the Cardinfo example to see how to determine the total card size.  Look in SD/utility/SDvolume::allocContiguous to see how it searches for available clusters to allocate.  I don't think it keeps a count of free or allocated clusters so you will have to go through every cluster and count the free ones.
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

DerekErb

Thank you for your quick reply.

I should have mentioned that I had already successfully tested the card size functionality. I was hoping there was a simple library function call to get the amount of free space on the card...

Another, very kludgy workaround, would be to take the total card size and loop through all of the stored files subtracting their current size from the total size. That would give an indication of how much size is left. That's definitely NOT what I am looking for... especially, as I think of it, as it would have to recurse through folders and subfolders as well!

Thanks...

johnwasser

You could add something like this to the SdVolume object:
Code: [Select]

// Count the number of free clusters
uint8_t SdVolume::freeSpace() {
  uint32_t freeCount = 0;

  // search the FAT for free clusters
  for (uint32_t cluster = 2;  cluster < clusterCount_; cluster++) {
    uint32_t f;
    if (!fatGet(endCluster, &f))
        return 0;

    if (f == 0)
        freeCount++;
    }

  return freeCount;
}
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

fat16lib

SD.h is a wrapper for an old version of SdFat and does not have a free space function.

Newer versions of SdFat have a free clusters function which gives free space.  Here is an example sketch:

Code: [Select]

#include <SdFat.h>
SdFat sd;
const uint8_t csPin = SS;
void setup() {
  Serial.begin(9600);
  if (!sd.begin(csPin)) sd.initErrorHalt();
  uint32_t freeKB = sd.vol()->freeClusterCount();
  freeKB *= sd.vol()->blocksPerCluster()/2;
  Serial.print("Free space KB: ");
  Serial.println(freeKB);
}
void loop() {}

Here is what it prints for 2GB and 8GB cards where KB is 1024 bytes:
Quote

Free space KB: 1949504
Free space KB: 7733952

Note that uint32_t is too small for free byte count for cards larger than 4GB.

Go Up