4

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

 1 year ago
source link: https://www.codeproject.com/Tips/5331981/Emulating-SD-Reader-Card-Change-Detection-When-You
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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:

Copy Code
// 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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK