Quantcast
Channel: Black Cat Microelectronics » J.P.
Viewing all articles
Browse latest Browse all 7

Arduino Leonardo and SD or MicroSD Cards

$
0
0

As a follow up to my Ethernet post, here are some notes for using the SD library for card access with Leonardo and other ATMEGA32U4 boards using Arduino 1.0.1 (Leonardo Bootloader and 1.0.1 IDE).

Unlike the Ethernet library, the SD library (which builds from the sdfatlib) handles the AVR SPI all on it’s own. The Ethernet library uses SPI library under the hood which sets up the micro controller pins for the SPI bus to work. When SD starts up it attempts to set up the pins as needed. The pins SPI are defined as 0 (SS), 1 (SCK), 2 (MOSI), 3 (MISO), I suspect this is in support of Teensyduino. However, these pins don’t translate to the correct pins when using the Arduino 1.0.1 IDE.

The pin definitions are used for initial pin direction (input/output) and software SPI. Software SPI is barely worth mentioning here. Using software SPI requires modification of the library files and intended for Arduino MEGA boards. Since the pin direction is set using pinMode the SPI interface doesn’t work because the pin directions aren’t set on the SPI pins, but if the pins are setup first the SD library works just fine.

If you’re using SPI for something besides SD (like Ethernet) you can start those devices first and the SD library will just work.

If you want to start the SD library before other SPI devices or only want to use the SD library you need to put two lines of code (highlighted in a sample below) before SD.begin. These lines setup the SCK and MOSI pins for output. Normally you would need to set the hardware SS pin to output as well, but this is taken care of by the Arduino code handling the USB serial port because this pins is used for a LED on Leonardo boards. The MISO pin needs to be set as an input pin, but the input direction is the power on default for pins.

pinMode(SCK, OUTPUT);
pinMode(MOSI, OUTPUT);

Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
  Serial.println("failed.");
  while(1);                // stay here forever
}
Serial.println("succeeded.");

Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles



Latest Images