Sdfat : A different approach to SD card ejection handling with sdfat

I am doing a project using an Adafruit AdaLogger rp2040 Feather.

I am using the normal sdfat stuff that was included in the package for the board:

I was struggling with handling the normal expected (no files open) eject as well as unexpected card ejects.

Since I only ever have one file open at a time, what I came up with is to not do an sd.begin() in setup().

When I need to open a file, I check SD_CS, then attempt sd.begin(), then open the file.

When the file access is complete, I close the file then call sd.end().

With this approach, I can eject the card without drama any time the file is closed.

Put the card back in, start logging again without any errors.

Here are snippets of what I'm doing:


  //Do NOT call sd.begin() in setup(). Wait until you need it.

  //When it is time to open the file and start writing:

  //See if there is a card inserted
  if(0 == digitalRead(SD_CD))
    {
    //No uSD card detected. Do not even try.
    return 0;
    }
  //There is a card, see if we can start the uSD system.
  if(0 == sd.begin(SD_CONFIG))
    {
    // Even though a card is detected, something still failed.
    return 0;
    }
  //Things look good so far. Try to open the file.
  our_file_handle = sd.open(filename,FILE_WRITE);    
  if(0 == our_file_handle)
    {
    // Even though a card is detected, and the sd system initialized,
    // some other something still went wrong.
    return 0;
    }

  // Now the file is open write as usual ...
  
  //When you have completed writing:
  
  //Release the file handle
  our_file_handle.close();
  //Shut down the sd system until we need to use it again
  sd.end();

So not only does this work well when the card is ejected between writes, it also recovers even if the card is ejected in the middle of a write. Well, the sd system recovers - the card may still be hosed as you would expect._* Here is how I handle writes:

  //Write this chunk of data
  bytes_written=our_file_handle.write(data,length_of_data);
  
  if(bytes_written != length_of_data)
    {
    //Some error. Likely an unexpected eject, or maybe the disk is full.
    //Try to recover as best we can.
    //Release the file handle
    our_file_handle.close();
    //Shut down the sd system until we need to use it again
    sd.end();
    return 0;
    }

_* Even after ejecting the card many times in the middle of a write, it still passes chkdsk. It is an exFAT -- maybe that matters. There are 0-byte files, but no card corruption.

Maybe this approach will be useful to someone.

Peace,

Isn't that the normal operation?

Maybe. Every example I have seen has sd.begin() in setup.

I guess I need to find better examples :thinking:

you are right - most examples do show this. begin in setup, open and close files as needed, never worry about card ejection :)

So thanks for sharing.