Click here to Skip to main content
15,882,113 members
Articles / Internet of Things / Arduino
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.54/5 (3 votes)
15 May 2022CPOL1 min read 4.9K   1   5
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)


Written By
United States United States
Just a shiny lil monster. Casts spells in C++. Mostly harmless.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA15-May-22 19:51
professionalȘtefan-Mihai MOGA15-May-22 19:51 
GeneralLanguage basics crash course Pin
Member 1563635415-May-22 10:38
Member 1563635415-May-22 10:38 
GeneralRe: Language basics crash course Pin
Test Tickle15-May-22 13:37
Test Tickle15-May-22 13:37 
GeneralRe: Language basics crash course Pin
honey the codewitch15-May-22 19:56
mvahoney the codewitch15-May-22 19:56 
GeneralRe: Language basics crash course Pin
Test Tickle16-May-22 8:33
Test Tickle16-May-22 8:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.