SD library, how to simulate a SD card ejection

Hi,

I have a custom board with an ATMEGA328P running a piece of code that writes a line on a file every loop() iteration.

The problem is: I have a circuit breaker to switch on/off the device and sometimes (let's say every twenty times I switch the board on) I cannot access the SD card. With an oscilloscope I checked the chipSelect signal and it is at the HIGH value (without changing) everytime this situation occurs.

If I eject the card and place it again or if I cut for a while the 3.3V that feeds the SD card the sketch starts running normally and the file is written. Restarting the MCU doesn't solve the problem because the 3.3V voltage is still available.

My question is: Is there any code instruction(s) I can use to simulate the SD card ejection?

Here is my sketch:

#include <SD.h>

#define MAINSDCS 10

void setup()
{
  Serial.begin(9600);
  
  SD.begin(MAINSDCS);
}

unsigned int fileID = 0;
void loop()
{
  File fp;
  char fileIDstr[10];
  
  memset(fileIDstr,'\0',10);
  ltoa(fileID,fileIDstr,10);
    
  fp = SD.open("tx.txt",FILE_WRITE);
  fp.println(fileIDstr);
  fp.close();
  
  fileID++;
}

Thanks in advance.

Given that fileID is an int, why are you using ltoa() to convert a long to a string? itoa() would be a better choice.

itoa() or ltoa() populate an array of chars, including the NULL at the end. It is not necessary to fill the array with STOP signs beforehand.

If interrupting the 3.3V line cures the issue, use a transistor to allow any digital pin to control the gate.

PaulS:
Given that fileID is an int, why are you using ltoa() to convert a long to a string? itoa() would be a better choice.

itoa() or ltoa() populate an array of chars, including the NULL at the end. It is not necessary to fill the array with STOP signs beforehand.

Yes, you are right.

If interrupting the 3.3V line cures the issue, use a transistor to allow any digital pin to control the gate.

I could do that but I am trying all the code possibilities before changing the hardware.

Thanks for your reply.