Arduino mega + SD memory card module

i basically found an arduino code to read all the files from the SD card and it won't work
can someone verify this code ?? and can someone tell me if this code is what i really want ?? (sorry i'm a beginner)
<<
#include <SPI.h>
#include <SD.h>

File root;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.print("Initializing SD card...");

if (!SD.begin(4)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");

root = SD.open("/");

printDirectory(root, 0);

Serial.println("done!");
}

void loop() {
// nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs) {
while (true) {

File entry =  dir.openNextFile();
if (! entry) {
  // no more files
  break;
}
for (uint8_t i = 0; i < numTabs; i++) {
  Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
  Serial.println("/");
  printDirectory(entry, numTabs + 1);
} else {
  // files have sizes, directories do not
  Serial.print("\t\t");
  Serial.println(entry.size(), DEC);
}
entry.close();

}
}

Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

In my experience the easiest way to tidy up the code and add the code tags is as follows

Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.

1 Like

How is the SD card module connected to the Mega ? Are you sure that you are using the correct pins for MISO, MOSI and SCK ? They are not pins 11, 12 and 13

yup they are connected correctly

Please humour me by detailing which pins you are using on the Mega for the 3 SPI connections

mosi with 11 + miso with 12 + sck with 13 + cs with 4

Oh dear

Read what I posted earlier

ah sorry i didn't see it ... if they're not 11, 12 and 13, then what they should be ?

Is Google broken where you are ?

See SPI - Arduino Reference

but don't get me started on the unnecessary (woke inspired) changes to the pin names. See https://docs.arduino.cc/learn/communication/spi/

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.