Loop Until SD Card is Detected

Is there a way to sit in a loop until a micro SD card is detected? I’ve tried the following code…

var sd = StorageController.FromName(SC20100.StorageController.SdCard);

bool sdCardMounted = false;
IDriveProvider drive;
do
{
	drive = FileSystem.Mount(sd.Hdc);
	try { if (drive.IsReady) sdCardMounted = true; } catch (System.NullReferenceException) { sdCardMounted = false; }
} while (!sdCardMounted);

This code will fall through if the card is initially inserted. However, if the card is not present when the program begins and is then inserted, drive.IsReady is remains NULL.

Thank you for the help.

are you using dev board, next to uSD there is CON mean connect I guess, you can connect that to gpio and track the level of then pin.

Thank you. I am using the fez-duino dev board. There is a CDN1 test point that appears to be floating with no microSD card and grounded with a microSD card. I can use that but was hoping for a software option…seem like what I have should work but it’s not.

I would like to add delay 1,2 second into the loop.

I tried up to a 5 second delay in the loop and it still did not work.

// I am using PC8 DAT0            
var pc8 = controller.OpenPin(SC20100.GpioPin.PC8); // use data0

// make the pin input low
pc8.SetDriveMode(GpioPinDriveMode.InputPullDown);
Thread.Sleep(10);

// make the pin float
pc8.SetDriveMode(GpioPinDriveMode.Input);

bool sdCardMounted = false;
IDriveProvider drive;
do
{
    Thread.Sleep(1000);
    if (pc8.Read() == GpioPinValue.High)
    {
        // Dispose() pins
        pc8.Dispose();
        pc8 = null;

        
        Thread.Sleep(50);
        System.GC.Collect();
        Thread.Sleep(50);

        Debug.WriteLine("Card detected.");

        var sd = StorageController.FromName(SC20100.StorageController.SdCard);
        drive = GHIElectronics.TinyCLR.IO.FileSystem.Mount(sd.Hdc);

        try
        {
            if (drive.IsReady)
            {
                sdCardMounted = true;
            }
        }
        catch (System.NullReferenceException)
        {                       
            sdCardMounted = false;
        }
    }
    else
    {
        Debug.WriteLine("Card is not detected.");
    }
    
    
} while (!sdCardMounted);

Usually, most SD cards use weak pull-ups on CMD and DAT0–DAT3.
I am trying to use PC8 (DAT0) for detection.
We will handle further detection internally in software later.