Pages: [1]   Go Down
Author Topic: SD.begin() causes "slowness" when SD card is not present  (Read 734 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 19
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi All,
Recently I've added SD card support to my project, it all went well although I had to do a good  face-lift to make sure there's enough memory for the highly demanding SD library.
However I have realized that if the microSD card is not present, and I call SD.begin() then any subsequent writes to Ethernet clients is really really slow (I/O is being done finally, but with lots of delays, even few seconds).
If I comment out SD.begin() then everything comes back to normal and Ethernet i/o is super-fast again.
Can you please advise?

This is the code I use in my setup() for initializing the SD card:


Code:
void setup() {
  Serial.begin(9600);
 
  // disable W5100 while setting up SD
  pinMode(10,OUTPUT);
  digitalWrite(10,HIGH);
 
  if (! SD.begin(4)) {
    Serial.println(F("Error cannot initialize SD card!"));
  }
}
Logged

Seattle, WA USA
Online Online
Brattain Member
*****
Karma: 551
Posts: 46219
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
This is the code I use in my setup() for initializing the SD card
That's less than 1/3 of the code you need to post.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 19
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I think I found what the problem was.

SD.begin() calls (among others) Sd2Card.init(), and inside init()'s code I found this lines of code (file Sd2Card.cpp):



that change the contents of the SPI Control and SPI Status registers respectively.

Later on, and because microSD card is on board, control goes to "fail" which simply calls chipSelectHigh() and returns false, but does not revert the contents of the SPI registers.

One solution to work-around this and still leave the library code untouched is to preserve the contents of the spi register and revert them in case of failure. This is how I fixed it in my sketch:

Code:
void setup() {
  Serial.begin(9600);
 
  // disable W5100 while setting up SD
  pinMode(10,OUTPUT);
  digitalWrite(10,HIGH);
 
  uint8_t spcr = SPCR;
  uint8_t spsr = SPSR;
  if (! SD.begin(4)) {
    Serial.println(F("Error cannot initialize SD card!"));
    SPCR = spcr;
    SPSR = spsr;
  }
}

Now I can still try to check if SD card is present, and still keep the Ethernet i/o fast.
Logged

Pages: [1]   Go Up
Jump to: