Skip to content

SD card example fail #3696

Closed
Closed
@maxcpr

Description

@maxcpr

a little bit changed example from IDE (SD listfiles), file listing moved to "loop".
Code stops listing microSD card after 17-20 loops (arduino nano).
(there is similar code, also listing files on microsd, that works fine on the same hardware)

/*
  Listfiles

 This example shows how print out the files in a 
 directory on a SD card 

 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 modified 2 Feb 2014
 by Scott Fitzgerald

 This example code is in the public domain.

 */
#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 Leonardo only
  }

  Serial.print("Initializing SD card...");
  digitalWrite(10, 1);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(4, 0);   // turn the LED on (HIGH is the voltage level)
  delay(2000); 
  while (!SD.begin(4)) {
    Serial.println("initialization failed!");
    delay(2000); 
//    return;
  }
  Serial.println("initialization done.");
}

void loop(){
  Serial.println("starting!");
  root = SD.open("/");
  printDirectory(root, 0);
  Serial.println("done!");
  delay(2000);
  pinMode(10, OUTPUT);
  pinMode(4, OUTPUT);
  digitalWrite(10, 1);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(4, 0);   // turn the LED on (HIGH is the voltage level)


}

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();
   }
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions