5

The question in short: On an Arduino UNO or Nano using the SD library, is it somehow possible to use the LED on pin 13 (or any other pin that is used by the library) again after finishing all SD operations?

Detailed explanation: In my sketch, during setup() I need to read some data from a file on the SD card, which is being closed again before leaving setup().

Now, I wanted to use the LED on pin 13 during loop() as a status indicator for the user, but it seems that after SD.begin(), pin 13 (and its LED) cannot be used as an OUTPUT anymore.

Here is a minimum sketch to show the behavior. It doesn't matter if I try to turn on the LED right after the call to SD.begin() in setup() or in loop():

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

#define SD_CS  4
#define LED    13

void setup() {
  pinMode(LED, OUTPUT);

  // This still works:
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);

  SD.begin(SD_CS);

  // This does not work anymore:
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);
}

void loop() {}

1 Answers1

10

It is possible to use the LED on pin 13 again by disabling the SPI bus that is used by the SD library to read/write data to/from the SD card. To disable the SPI bus, simply call SPI.end() after closing the file on the SD card.

  • 1
    Agreed. Betwen `SPI.begin()` and `SPI.end()` the hardware takes over that pin. – Nick Gammon Jul 25 '15 at 21:38
  • 3
    Does anyone know, why the SD library has no `.end()`? Apparently you don't have to explicitly call `SPI.begin()` in your sketch, as `SD.begin()` seems to wrap this. So I think, a call to `SPI.end()` should also be wrapped in some complementary method like `SD.end()`. Should this be filed as a bug report/wishlist item to the library developers? Or is there any reason why there is no method like this? – Johannes Maibaum Jul 27 '15 at 07:31
  • Sounds odd to me. You could query it with the developers. – Nick Gammon Jul 27 '15 at 20:32
  • Any updates on your followup question @JohannesMaibaum? – Jaroslav Záruba Mar 01 '17 at 11:53
  • 1
    @JaroslavZáruba: No, actually. I just checked the [online reference for the SD library](https://www.arduino.cc/en/Reference/SD) again, but still there is no `SD.end()` or similar. But simply calling `SPI.end()` worked and works for me. – Johannes Maibaum Mar 12 '17 at 16:33