Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Arduino

Emulating SD Reader Card Change Detection When You Don't Have It

4.54/5 (3 votes)
15 May 2022CPOL1 min read 5.4K  
Detect when your SD card gets removed and recover gracefully, even without a card change pin.
This tip shows how to emulate SD Reader card change detection when you don't have it.

Introduction

I recently built a MIDI "score sampler" project that reads MIDI files off of an SD card. The SD readers I have do not have a pin to detect when a card has been removed or inserted, although some do. Fortunately, you can more or less emulate this feature in software, albeit less efficiently. The advantage of this technique, other than working with SD readers that don't have a card change pin is you don't need to tie up one additional GPIO pin to use it.

Using the Code

Understanding what we're doing is pretty simple. The SD card will error on any IO operations once the card is removed, so we check for those. When that happens, we simply run the following code - tested on an ESP32 - some platforms may have a slightly different signature for the begin() method:

C++
// the CS line of the reader
#define SD_CS 15
...
while(true) {
    SD.end();
    SD.begin(SD_CS,SPI);
    File file=SD.open("/","r");
    if(!file) {
        delay(1);
    } else {
        file.close();
        break;
    }
}
// an SD card was re-inserted 
// once we get here

We begin and end SD and try to read the root directory repeatedly in our loop. It will fail until there's a root directory to read from, meaning a valid SD card is inserted. We have to begin and end because the SD library caches errors and won't try again once it fails, at least until the whole library is restarted.

History

  • 15th May, 2022 - Initial submission

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)