]> git.piffa.net Git - arduino/blob - books/pdummies/Libraries/SD/examples/listfiles/listfiles.pde
first commit
[arduino] / books / pdummies / Libraries / SD / examples / listfiles / listfiles.pde
1 /*
2   SD card basic file example
3  
4  This example shows how to create and destroy an SD card file   
5  The circuit:
6  * SD card attached to SPI bus as follows:
7  ** UNO:  MOSI - pin 11, MISO - pin 12, CLK - pin 13, CS - pin 4 (CS pin can be changed)
8   and pin #10 (SS) must be an output
9  ** Mega:  MOSI - pin 51, MISO - pin 50, CLK - pin 52, CS - pin 4 (CS pin can be changed)
10   and pin #52 (SS) must be an output
11  ** Leonardo: Connect to hardware SPI via the ICSP header
12
13  created   Nov 2010 by David A. Mellis
14  modified 9 Apr 2012 by Tom Igoe
15  modified 13 June 2012 by Limor Fried
16  
17  This example code is in the public domain.
18          
19  */
20 #include <SD.h>
21
22 File root;
23
24 // change this to match your SD shield or module;
25 //     Arduino Ethernet shield: pin 4
26 //     Adafruit SD shields and modules: pin 10
27 //     Sparkfun SD shield: pin 8
28 const int chipSelect = 4;
29
30 void setup()
31 {
32   // Open serial communications and wait for port to open:
33   Serial.begin(9600);
34    while (!Serial) {
35     ; // wait for serial port to connect. Needed for Leonardo only
36   }
37
38
39   Serial.print("Initializing SD card...");
40   // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
41   // Note that even if it's not used as the CS pin, the hardware SS pin 
42   // (10 on Arduino Uno boards, 53 on the Mega) must be left as an output 
43   // or the SD library functions will not work. 
44   pinMode(SS, OUTPUT);
45
46   if (!SD.begin(chipSelect)) {
47     Serial.println("initialization failed!");
48     return;
49   }
50   Serial.println("initialization done.");
51
52   root = SD.open("/");
53   
54   printDirectory(root, 0);
55   
56   Serial.println("done!");
57 }
58
59 void loop()
60 {
61   // nothing happens after setup finishes.
62 }
63
64 void printDirectory(File dir, int numTabs) {
65   // Begin at the start of the directory
66   dir.rewindDirectory();
67   
68   while(true) {
69      File entry =  dir.openNextFile();
70      if (! entry) {
71        // no more files
72        //Serial.println("**nomorefiles**");
73        break;
74      }
75      for (uint8_t i=0; i<numTabs; i++) {
76        Serial.print('\t');   // we'll have a nice indentation
77      }
78      // Print the 8.3 name
79      Serial.print(entry.name());
80      // Recurse for directories, otherwise print the file size
81      if (entry.isDirectory()) {
82        Serial.println("/");
83        printDirectory(entry, numTabs+1);
84      } else {
85        // files have sizes, directories do not
86        Serial.print("\t\t");
87        Serial.println(entry.size(), DEC);
88      }
89      entry.close();
90    }
91 }
92
93
94