LCD lagging after SD.begin()

Hello,

I'm facing some problems related to the responsiveness of an LCD when it is used with an SD Card reader at the same time. They both use SPI to communicate and the LCD is quite fast until I start using the SD Card.

I did a small benchmark to test the difference and it is quite big! =(

#include <Adafruit_GFX.h> 
#include <Adafruit_ST7735.h>
#include <SPI.h>
#include <SD.h>

Adafruit_ST7735 tft = Adafruit_ST7735(10, 9, 8);
int timelapse;
void setup()
{
  Serial.begin(9600);
  tft.initR(INITR_REDTAB);
  tft.fillScreen(ST7735_BLACK);
}

void loop()
{
  Serial.println( "Press any key to start..." );
  while (!Serial.available()>0 ) {}
  Serial.read();
  
  Serial.print( "Time spent to print 90 interations to screen: " );
  timelapse = millis();
  test();
  Serial.print( (millis() - timelapse) );
  Serial.println( "ms." );
  
  Serial.print( "Time spent to print 90 interations to screen (after SD.begin()): " );
  SD.begin(4);
  timelapse = millis();
  test();
  Serial.print( (millis() - timelapse) );
  Serial.println( "ms." );  
}

void test()
{
  tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
  tft.setTextSize(5);
  for ( int i = 10; i < 100; i++ )
  {
    tft.setCursor(40, 50);
    tft.print( i );
  }
}

And these were the results:

Press any key to start...
Time spent to print 90 interations to screen: 1929ms.
Time spent to print 90 interations to screen (after SD.begin()): 34613ms.

I need to be able to show data on the screen without lag while saving a few bytes (about 100) every 5 seconds. Any ideas? Thanks!

After searching a bit more I found out the reason why this happens (Thanks afasias!):

This is due to some SPI Control and SPI Status problems (registers are changed and they are not reverted after using the SD begin). You can read more here: http://arduino.cc/forum/index.php/topic,122207.0.html

Thanks!

Yes, the SD code doesn't cooperate with other SPI users.

In fact its worse than that, it leaves the SPI set to a very slow mode indeed if there is a failure during SD card initialization
(for instance no card is inserted). If SD init succeeds it leaves the SPI clock speed at 4MHz which is pretty fast.

The builtin SPI library is a minimal library with no support for different clock speeds or bit orders for different
devices - what is more the SD library doesn't use it so even if SPI library was smarter it wouldn't work.