Updated on 2022-05-15
Detect when your SD card gets removed and recover gracefully, even without a card change pin.
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.
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:
// 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.