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 | ** MOSI - pin 11
|
8 | ** MISO - pin 12
|
9 | ** CLK - pin 13
|
10 | ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)
|
11 |
|
12 | created Nov 2010
|
13 | by David A. Mellis
|
14 | modified 9 Apr 2012
|
15 | by Tom Igoe
|
16 |
|
17 | This example code is in the public domain.
|
18 |
|
19 | */
|
20 | #include <SPI.h>
|
21 | #include <SD.h>
|
22 |
|
23 | const int chipSelect = 4;
|
24 |
|
25 | File myFile;
|
26 |
|
27 | void setup() {
|
28 | // Open serial communications and wait for port to open:
|
29 | Serial.begin(9600);
|
30 | while (!Serial) {
|
31 | ; // wait for serial port to connect. Needed for native USB port only
|
32 | }
|
33 |
|
34 | Serial.print("Initializing SD card...");
|
35 |
|
36 | if (!SD.begin(chipSelect)) {
|
37 | Serial.println("initialization failed!");
|
38 | while (1);
|
39 | }
|
40 | Serial.println("initialization done.");
|
41 |
|
42 | if (SD.exists("example.txt")) {
|
43 | Serial.println("example.txt exists.");
|
44 | } else {
|
45 | Serial.println("example.txt doesn't exist.");
|
46 | }
|
47 |
|
48 | // open a new file and immediately close it:
|
49 | Serial.println("Creating example.txt...");
|
50 | myFile = SD.open("example.txt", FILE_WRITE);
|
51 | myFile.close();
|
52 |
|
53 | // Check to see if the file exists:
|
54 | if (SD.exists("example.txt")) {
|
55 | Serial.println("example.txt exists.");
|
56 | } else {
|
57 | Serial.println("example.txt doesn't exist.");
|
58 | }
|
59 |
|
60 | // delete the file:
|
61 | Serial.println("Removing example.txt...");
|
62 | SD.remove("example.txt");
|
63 |
|
64 | if (SD.exists("example.txt")) {
|
65 | Serial.println("example.txt exists.");
|
66 | } else {
|
67 | Serial.println("example.txt doesn't exist.");
|
68 | }
|
69 |
|
70 | myFile = SD.open("/");
|
71 |
|
72 | printDirectory(myFile, 0);
|
73 |
|
74 | Serial.println("done!");
|
75 | }
|
76 |
|
77 | void printDirectory(File dir, int numTabs) {
|
78 | while (true) {
|
79 |
|
80 | File entry = dir.openNextFile();
|
81 | if (! entry) {
|
82 | // no more files
|
83 | break;
|
84 | }
|
85 | for (uint8_t i = 0; i < numTabs; i++) {
|
86 | Serial.print('\t');
|
87 | }
|
88 | Serial.print(entry.name());
|
89 | if (entry.isDirectory()) {
|
90 | Serial.println("/");
|
91 | printDirectory(entry, numTabs + 1);
|
92 | } else {
|
93 | // files have sizes, directories do not
|
94 | Serial.print("\t\t");
|
95 | Serial.println(entry.size(), DEC);
|
96 | }
|
97 | entry.close();
|
98 | }
|
99 | }
|
100 |
|
101 |
|
102 | void loop() {
|
103 | // nothing happens after setup finishes.
|
104 | }
|